簡體   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