React to improve the reusability of components

1. Properties props and combinations

1. props.children

Rendering props.children where needed custom content

function Dialog (The props) { // common components 
  return (
     <div>
      <h1 className="dialog-title">{props.title}</h1>
      <p className="dialog-message">
        {props.message}
      </p>
      {
        props.children // In the final assembly the user can customize to add content 
      }
     </ div>
   )
}
class SignUpDialog extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      loginName: ''
    }
  }
  handleChange = (e) => {
    this.setState({
      loginName: e.target.value
    })
  }
  render() {
    return (
      <Dialog 
        title="welcom" 
        message="Thank you for visiting our spacecraft!"
      >
        <input 
          type="text" 
          value={this.state.loginName} 
          onChange={this.handleChange}
        />
        <button>
          registered
        </button>
      </Dialog>
    )
  }
}

2. The component is passed to another component as a variable

function Dialog (The props) { // common components 
  return (
     <div>
      {
        props.selfDefine ||  <h1 className="dialog-title">{props.title}</h1>
      }
      <p className="dialog-message">
        {props.message}
      </p>
    </div>
  )
}
class SignUpDialog extends React.Component {
  render() {
    H2 const = <H2> This is the definition of the title </ H2>;
     return (
       < Dialog
        title="welcom" 
        message="Thank you for visiting our spacecraft!"
        selfDefine={h2}
      />
    )
  }
}

 

Guess you like

Origin www.cnblogs.com/lyraLee/p/11897154.html