如何在所有组件中使用相同的代码行?

时间:2017-08-20 17:20:24

标签: reactjs

我正在做一个反应应用程序,其中四个组件共享一些相同的行,所以我如何包装这些行并在所有组件中使用:

class PersonalInformation extends Component{
render(){
return(
  <div className="form-place">
    <h3>Personal Information</h3>
    <Form onSubmit={this.props.handleSubmit} ref="form">
      <fieldset disabled={this.props.disabled}>
        <Input type="text" name="firstName" title="FirstName" value=""/>
        <Input type="text" name="lastName" title="LastName" value=""/>
        <Input type="text" name="fatherName" title="Fathers's Name" value=""/>
        <Input type="text" name="motherName" title="Mother's Name" value=""/>
      </fieldset>
      <button>{this.props.buttonName}</button>
    </Form>
  </div>
)
}
}

下面这些行在所有组件中都是通用的,所以我如何在所有组件中重用这些行:

<Form onSubmit={this.props.handleSubmit} ref="form">
  <fieldset disabled={this.props.disabled}>

  </fieldset>
  <button>{this.props.buttonName}</button>
</Form>

1 个答案:

答案 0 :(得分:1)

您可以创建包含Form

common code组件
import Form from '..yourlibrary'; //your form library here
const MyForm = (props) => (
 <Form onSubmit={props.handleSubmit}>
   <fieldset disabled={props.disabled}>{props.children}</fieldset>
   <button>{props.buttonName}</button>
</Form>)
export default MyForm;

然后像这样使用它

import MyForm from './form'; // or whatever is your path

class PersonalInformation extends Component{
  render(){
    return(
     <div className="form-place">
      <h3>Personal Information</h3>
       <MyForm onSubmit={this.props.handleSubmit}
             ref="form"
             disabled={this.props.disabled}
             buttonName={this.props.buttonName}>
         <Input type="text" name="firstName" title="FirstName" value=""/>
         <Input type="text" name="lastName" title="LastName" value=""/>
         <Input type="text" name="fatherName" title="Fathers's Name" value=""/>
         <Input type="text" name="motherName" title="Mother's Name" value=""/>
      </MyForm>
     </div>);
   }
}

此处,Input集将作为children传递给MyForm组件。