繁体   English   中英

创建可重用组件的正确方法是什么?

[英]What is the proper way to create reusable components react

学习反应并构建一个有很多输入字段的页面。
我想为不同的输入类型创建组件,以便以后我可以使用它们而不是一遍又一遍地创建输入。

我写过这样的东西,但我重复了很多东西,所以我认为可能有更好的方法来做到这一点。

class BaseInput extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <input
        id={this.props.id}
        name={this.props.name}
        type={this.props.type}
        value={this.props.value}
        onChange={this.props.onChange}
        placeholder={this.props.placeholder}
        required
      />
    );
  }
}

export function PasswordInput(props) {
  return (
    <BaseInput
      id={props.id}
      name={props.name}
      type="password"
      value={props.value}
      onChange={props.onChange}
      placeholder={props.placeholder}
    />
  );
}

export function TextInput(props) {
  return (
    <BaseInput
      id={props.id}
      name={props.name}
      type="text"
      value={props.value}
      onChange={props.onChange}
      placeholder={props.placeholder}
    />
  );
}

您可以使用扩展运算符来减少代码。

class TextInput extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <input {...this.props} />;
  }
}

export default TextInput;

这样您甚至不需要单独的 PasswordInput 组件。

<TextInput id="name" type="text" placeholder="Your Name" />
<TextInput id="password" type="password" />

假设您的可重用组件名为FormInput

组件定义应如下所示:

const FormInput = (props: any) => {
  const [value, setValue] = useState(props.value);
  useEffect(() => {
    setValue(props.value);
  }, [props.value])

  return ( 
    <input
       autoComplete={props.autoComplete}
       name={props.name}
       type={props.type}
       id={props.id} 
       value={props.value}
       data-index={props.index} 
       onChange={props.onChange} 
       disabled={props.disabled}
       ariaLabelledBy={props.ariaLabelledBy} 
       required={props.required}/>
  )
};

在你想要使用它的页面中,你可以简单地调用组件,将所有的 props 传递给组件并在页面上实现 onChange 事件处理程序:

假设您要调用登录页面上的输入组件:

const LoginPage = (props: any) => {
    ... // you have some useEffect etc. that is related to the business logic of the page

    const handleChange = (event: any) => {
      // put your logic here
    }

   return (
        ... // other HTML elements/components

       <FormInput type="text" onChange={handleChange} id="test" value="John Doe" ... />
   )
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM