与多个组件反应HOC

我想创建一个React HOC,理想情况下它将接收两个组件而不是一个包装的组件,并在它们之间切换。也就是说,在下面的代码中,它们分别代替<h3>component one</h3>和<h3>component two<h3>代表子组件。我将如何做到这一点?有关如何编写此HOC的一些伪代码:


<HOC>

  <ComponentOne />

  <ComponentTwo />

</HOC>


<HOC

  componentOne={<ComponentOne />}

  componentTwo={<ComponentTwo />}

/>


hoc(componentOne, componentTwo)

class HOC extends React.Component {

    constructor() {

    super();

    this.state = {

      onClick: false,

    };

    this.handleClick = this.handleClick.bind(this);

  }


  handleClick() {

    this.setState({onClick: !this.state.onClick});

  }

    


  render() {

    return (

      <div>

        <button onClick={this.handleClick}>Click Me!</button>

        { 

          this.state.onClick ?

            <h3>component one</h3> :

            <h3>component two</h3>

        }

      </div>

    );

  }

}




ReactDOM.render(<HOC />, app);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>


慕容3067478
浏览 169回答 2
2回答

海绵宝宝撒

如果一个组件有多个子代,this.props.children则将是一个数组。class HOC extends React.Component {&nbsp; &nbsp; // ... rest of code ....&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; const { onClick } = this.state;&nbsp; &nbsp; &nbsp; &nbsp; const { children } = this.props;&nbsp; &nbsp; &nbsp; &nbsp; return !onClick ? children[0] : children[1];&nbsp; &nbsp; }}然后像这样使用它:<HOC>&nbsp; &nbsp; <div>Child One</div>&nbsp; &nbsp;&nbsp; &nbsp; <div>Child Two</div></HOC>显然,这仅适用于两个孩子,但是您可以通过将整数传递给<HOC>props来告诉它选择哪个孩子来扩展它。编辑快速浏览文档后,这是我上面编写的更好的版本,因为this.props.children它不是数组,而是一个不透明的数据结构:class HOC extends React.Component {&nbsp; &nbsp; // ... rest of code ...&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; const { onClick } = this.state;&nbsp; &nbsp; &nbsp; &nbsp; const children = React.Children.toArray(this.props.children);&nbsp; &nbsp; &nbsp; &nbsp; return !onClick ? children[0] : children[1];&nbsp; &nbsp; }}

qq_笑_17

我不确定我是否理解你。为什么需要将它设为HOC?如果您将组件作为道具传递:<HOC&nbsp; componentOne={<ComponentOne />}&nbsp; componentTwo={<ComponentTwo />}/>然后,您将可以使用道具访问它们。render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={this.handleClick}>Click Me!</button>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.state.onClick ?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.props.componentOne :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.props.componentTwo&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript