如何将数据传递给子节点而不在props中指定它

时间:2018-05-04 11:19:57

标签: reactjs

最近我们得到了Context支持。 让我们看下一个例子:

<Consumer>{value => <Child value={value} />}</Consumer>

如何制作发送&#34;值&#34;的组件?它的孩子一样吗? 我的意思是

<MyComponent>{value => ...}</MyComponent>

2 个答案:

答案 0 :(得分:3)

您使组件使用render props callback pattern之类的

class MyComponent extends React.Component {
   state = {
      value: 'abc'
   }
   render() {
      return React.Children.only(this.props.children)(this.state.value)
   }
}

然后你可以像

一样使用它
<MyComponent>{value => ...}</MyComponent>

答案 1 :(得分:2)

也许是higher order component (HOC)

function withContext(Component) {
  return WithContext = (props) => (
    <Consumer>
     {
       value => <Component {...props} value={value} />
     }
    </Consumer>
  )
}

let MyComponent = ({ value }) => (
  <div>
    {value}  // if value is something that can be rendered
  </div>
)

MyComponent = withContext(MyComponent);

render props

const MyComponent = (props) => (
  <Consumer>
    {value => props.children(value)}
  </Consumer>
)

const example = (
  <MyComponent>
   {value => <div>{value}</div>} // children prop has to be function now
  </MyComponent>
)