2016-06-26 1 views
4

Прошу вас, пожалуйста. Я просто изучаю Reactjs и придерживаюсь точки.Как передать реквизиты (оба состояния и функции) на компонент дочернего маршрутизатора

приложение-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() не стреляет. Как передать реквизит на {this.props.children} (т. Е. Аудитория или спикер) на APP?

обновление:

APP.js визуализации():

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

}); 
+0

Используйте 'React.children.map (this.props.children ...' 'с прописной Children'. –

ответ

1

Там это сочетание 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, 
      ... 
     }); 
    )} 
} 
+0

Предположим, я передаю все состояния '{React.cloneElement (this.props.children, {... this.state})}'. Это передает все реквизиты, но если мне нужно передать функцию prop ребенку, как бы я это сделал? – Robin

+0

Если у вас есть функция, определенная уже где-то, просто передайте ссылку: 'propFn: fnReference ..' –

+0

Это '{React.cloneElement (this.props.children, {... this.state, emit: this.emit})} 'дает мне ошибку:' Uncaught TypeError: Невозможно прочитать свойство 'реквизиты' неопределенного'. – Robin

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/

+0

Предположим, я передаю все состояния '{React.cloneElement (this.props.children, {... this.state})}'. Это пропускает все реквизиты, но если мне пришлось передать «функцию» в качестве опоры для ребенка, как мне это сделать? – Robin

+0

Пожалуйста, проверьте, я обновил пример. Вы можете просто передать функцию реквизита для детей с одинаковым шаблоном –

Смежные вопросы