提高React组件的复用性

1. 使用props属性和组合

1. props.children

在需要自定义内容的地方渲染props.children

function Dialog(props) { //通用组件
  return (
    <div>
      <h1 className="dialog-title">{props.title}</h1>
      <p className="dialog-message">
        {props.message}
      </p>
      {
        props.children //在组件最后用户可以自定义添加内容
      }
    </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>
          注册
        </button>
      </Dialog>
    )
  }
}

2. 将组件作为变量传递到另一个组件

function Dialog(props) { //通用组件
  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() {
    const h2 = <h2>这是自定义的标题</h2>;
    return (
      <Dialog 
        title="welcom" 
        message="Thank you for visiting our spacecraft!"
        selfDefine={h2}
      />
    )
  }
}

猜你喜欢

转载自www.cnblogs.com/lyraLee/p/11897154.html