如何将props(状态和函数)传递给子路由器组件

时间:2016-06-26 12:25:20

标签: javascript reactjs react-router

请耐心等待。我只是学习Reactjs并且坚持到了某一点。

APP-client.js

ReactDOM.render((
    <Router history={hashHistory}>
        <Route path="/" component={APP}>
            <IndexRoute component={Audience}/>
            <Route path="speaker" component={Speaker}/>
            <Route path="board" component={Board}/>
        </Route>
    </Router>
), document.getElementById('react-container'));

APP.js

var APP = React.createClass({

    getInitialState() {
        return {
            status: 'disconnected',
            title: ''
        }
    },

  emit(eventName, payload) {
        this.socket.emit(eventName, payload);
    },

  render() {
    return (
        <div>
            <Header title={this.state.title} status={this.state.status}/>
            {this.props.children}
        </div>
        );
  }
});

Audience.js:

var Audience = React.createClass({
    render() {
        return (<h1>Audience: {this.props.title}</h1>);
    }
});

该页面显示所有组件,但页面中未显示this.props.title,并且emit()未触发。如何将道具传递给APP上的{this.props.children}(即观众或演讲者)?

更新

APP.js render():

render() {
    const _this = this;
    return (
        <div>
            <Header title={this.state.title} status={this.state.status}/>
            { React.children.map(this.props.children, (child, index) => {
                    //Get props of child
                   // const childProps = child.props;

                   //do whatever else you need, create some new props, change existing ones
                   //store them in variables

                   return React.cloneElement(child, {
                       // ...childProps, //these are the old props if you don't want them changed
                       // ...someNewProps,
                       // someOldPropOverwritten, //overwrite some old the old props
                       ..._this.state,
                       emit: _this.emit
                   });
                })
            }
        </div>
        );
  }

});

2 个答案:

答案 0 :(得分:1)

React为您提供了一系列API,可以准确地处理您不确定如何实现的内容(way to pass props to components rendered by this.props.children

首先,您需要查看cloneElement

它基本上会使用一个React元素,克隆它,并返回另一个带有道具的东西,你可以根据自己的需要完全改变,改变或替换。

此外,将它与Children Utilities - 循环结合通过提供给顶级组件的子项并对每个元素进行必要的更改。

您可以找到一个更全面的答案,我就下面最近提出的问题提供了一个非常相似的主题:

changing-components-based-on-url-with-react-router

基本上,有些东西:

render() {
  const _this = this;
  return (
    {React.Children.map(this.props.children, (child, index) => {
       //Get props of child
       const childProps = child.props;

       //do whatever else you need, create some new props, change existing ones
       //store them in variables

       return React.cloneElement(child, {
           ...childProps, //these are the old props if you don't want them changed
           ...someNewProps,
           someOldPropOverwritten, //overwrite some old the old props
           ..._this.state,
           someFn: _this.someFn,
           ...
       });
     )}
}

答案 1 :(得分:1)

使用Api React.children迭代父元素并使用React.cloneElement克隆每个元素

var Child = React.createClass({
  render: function() {
        return (<div onClick={() =>  this.props.doSomething(this.props.value)}>Click Me</div>);
  }
});


var Audience = React.createClass({
  render: function() {
        return (<div>{this.props.title}</div>);
  }
});

var App = React.createClass({

  doSomething: function(value) {
    console.log('child with value:', value);
  },

  render: function() {
    var childrenWithProps = React.Children.map(this.props.children, (child) => React.cloneElement(child, { title: "test", doSomething: this.doSomething }));
    return <div>{childrenWithProps}</div>
  }
});

ReactDOM.render(
  <App>
    <Child value="2"/>
    <Audience/>
  </App>,
    document.getElementById('container')
);

https://jsfiddle.net/ysq2281h/