You need to enable JavaScript to run this app. React TypeScript Storybook开发自定义Input组件:onChange回调同步输入值失效求助
优惠活动
大模型
产品
解决方案
定价
更多

React TypeScript Storybook开发自定义Input组件:onChange回调同步输入值失效求助

问题根因
  • 违反React Hooks调用规则:在Storybook的模块顶层直接调用useState,Hooks必须在函数组件/自定义Hook内部执行,模块顶层代码不属于组件渲染周期,无法触发正常的状态更新逻辑,会直接抛出无效Hook调用的错误。
  • 入参命名不匹配:自定义Input组件接收的输入变更回调入参名为onChangeInput,但Story的配置中传入的是onChange,回调根本没有被组件捕获执行。
  • 静态值绑定无效:将模块加载时获取的初始localValue直接传入Story的args,args是模块加载阶段生成的静态配置快照,不会随组件内部的状态变化同步更新,就算状态触发变更,传给Input的value也永远是初始空值。
修正后实现

1. 优化Input组件类型定义

将原实现中类型为any的回调参数替换为明确的函数类型,提升类型可靠性:

import React from 'react'

export type Props = {
  /**
   * This is the Label text value
   */
  labelText?: string,
  /**
   * Placeholder text for input
   */
  placeholder?: string,
  /**
   * Classes defined here will be appended to the input's default classes
   */
  className?: string,
  /**
   * Value attribute of Input
   */
  value?: string,
  /**
   * Name attribute of Input
   */
  name?: string,
  /**
   * Label for attribute
   */
  htmlFor?: string,
  /**
   * Callback for when user typing in Input
   */
  onChangeInput: (inputValue: string) => void,
}

/**
 * Generic input component.
 */
export function Input({labelText, placeholder='', className='', value='', name='', htmlFor='', onChangeInput}:Props) {    
    return (
        <div>
            <label className='text-text-01-normal font-medium text-sm leading-5' htmlFor={htmlFor}>
                {labelText}
            </label>
            <div className="relative">
                <input
                    id={htmlFor}
                    className={[
                        "relative w-64 pl-3 h-8 py-2 border rounded bg-ui-03 border-ui-06 text-text-01-normal leading-5 text-sm text-left hover:bg-ui-03 hover:border-ui-07 focus:bg-ui-03 focus:outline-none focus:border-interactive-01-active active:bg-ui-03",                        
                        className
                        ].join(' ')} 
                    placeholder={placeholder}
                    value={value}
                    name={name}
                    onChange={ (e) => { onChangeInput(e.target.value) }}
                />
            </div>
        </div>
    )
}   

2. 修正后的Storybook配置

import React, { useState } from 'react';
import { Story, Meta } from '@storybook/react';
import { withDesign } from 'storybook-addon-designs'

import { Input, Props } from './Input';

export default {
  title: 'General/Input',
  component: Input,
  decorators: [withDesign],
  parameters: {
    design: {
      type: 'figma',
    },
  },
} as Meta;

// Template本身是React函数组件,可在内部合规调用Hooks
const Template: Story<Props> = (args: Props) => {
  // 在组件渲染周期内初始化状态,符合React Hooks调用规则
  const [localValue, setLocalValue] = useState<string>('');
  const handleChangeInput = (inputValue: string) => {
    setLocalValue(inputValue);
  };
  
  // 动态绑定状态与回调,覆盖静态args中的对应配置
  return (
    <Input 
      {...args} 
      value={localValue} 
      onChangeInput={handleChangeInput} 
    />
  );
};

export const Default: Story<Props> = Template.bind({});
// 静态args仅存放与动态状态无关的基础配置
Default.args = {
  labelText: 'Label',
  placeholder: 'Placeholder',
  name: 'test-name',  
  htmlFor: 'test-for',
} as Partial<Props>;
Default.parameters = {
  design: {
    url: 'https://www.figma.com/to-some-design-url'
  }
}
实现逻辑说明
  • 将useState的调用移到Template函数内部,完全符合React Hooks的调用规则,每个Story渲染时会生成独立的组件状态,不会出现无效Hook报错。
  • 修正入参命名:将原来错传的onChange替换为组件实际接收的onChangeInput,确保输入事件能正常触发状态更新。
  • 状态绑定嵌入组件渲染流程,每次用户输入触发状态更新时,组件会自动重渲染,将最新的输入值作为value传入自定义Input组件,实现受控输入的实时展示效果。
  • 静态args仅保留固定配置项,避免静态快照覆盖组件内部的动态值绑定。

内容的提问来源于stack exchange,提问作者sefirosu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.18 12:06:03