简体   繁体   English

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

[英]How to pass props (both states and functions) to the child router component

Please bear with me. 请多多包涵。 I just learning Reactjs and stuck at a point. 我只是学习Reactjs并且坚持到了某一点。

app-client.js 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 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: Audience.js:

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

The page is showing all the components, but this.props.title is not showing in the page, and the emit() is not firing. 该页面显示所有组件,但this.props.title未显示在页面中,并且emit()未触发。 How do I pass the props to {this.props.children} (ie, Audience or Speaker) on the APP? 如何将道具传递给APP上的{this.props.children} (即观众或演讲者)?

update : 更新

APP.js render(): 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>
        );
  }

});

There's a combination of APIs that React provides you with that will take care of exactly what you're not certain about of how to achieve ( way to pass props to components rendered by this.props.children ) React为您提供了一系列API,它们将完全解决您不确定如何实现的问题( way to pass props to components rendered by this.props.children

First, you need to take a look at cloneElement 首先,您需要查看cloneElement

It will basically take a React element, clone it, and return another with props that you can change, alter or replace entirely based on your needs. 它基本上会采用一个React元素,克隆它,并返回另一个带有道具,你可以根据自己的需要完全改变,改变或替换。

Furthermore, combine it with the Children Utilities - loop through the children that were provided to your top level component and make the necessary changes to each element individually. 此外,将它与Children Utilities结合 - 循环通过提供给顶级组件的子项,并分别对每个元素进行必要的更改。

You can find a more comprehensive answer that I provided on a very similar topic for a question that was asked recently below: 您可以找到一个更全面的答案,我在下面提到的一个问题的非常相似的主题上提供了答案:

changing-components-based-on-url-with-react-router 更换的组件为基础上的URL,与反应的路由器

Basically, something along the lines of: 基本上,有些东西:

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,
           ...
       });
     )}
}

Iterate parent element using Api React.children and clone each element using React.cloneElement 使用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/ https://jsfiddle.net/ysq2281h/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM