2016-04-14 4 views
0

У меня есть приложение React.js, который строится так:Отправка состояния родительских компонентов с React.js

// App component - represents the whole app 
App = React.createClass({ 
    render() { 
     return (

      <div> 
      <Landing /> 
      <Description /> 
      <Skills/> 
      </div> 

    ); 
    } 
}); 

где «Посадка», «Описание» и «навыки» все дети компоненты компонент приложения.

В Landing, у меня есть ребенок компонент под названием Social Menu, который вызывается с помощью:

<SocialMenu items={ ['Home', 'Services', 'About', 'Contact us']} /> 

Это выглядит следующим образом:

SocialMenu = React.createClass({ 

    getInitialState: function(){ 
     return { focused: 0 }; 
    }, 

    componentDidMount: function() { 
     MichaelReactStore.addChangeListener(this.state.focused); 
    }, 

    clicked: function(index){ 

     // The click handler will update the state with 
     // the index of the focused menu entry 

     this.setState({focused: index}); 
    }, 

    render: function() { 

     // Here we will read the items property, which was passed 
     // as an attribute when the component was created 

     var self = this; 

     // The map method will loop over the array of menu entries, 
     // and will return a new array with <li> elements. 

     return (
      <div> 
       <ul className="testblocks">{ this.props.items.map(function(m, index){ 

        var style = ''; 

        if(self.state.focused == index){ 
         style = 'focused'; 
        } 

        // Notice the use of the bind() method. It makes the 
        // index available to the clicked function: 

        return <li key={index} className={style} onClick={self.clicked.bind(self, index)}>{m}</li>; 

       }) } 

       </ul> 



       <p>Selected: {this.props.items[this.state.focused]}</p> 

       <ItemDetails item={ this.props.items[this.state.focused] } /> 

      </div> 
     ); 

    } 
}); 

ItemDetails = React.createClass({ 

    render: function() { 

     return (
      <div>{this.props.item}</div> 
     ); 
    } 

}); 

То, что я хотел бы сделать, это «Отправить укажите «вверх» в компонент приложения из социального меню. Затем я хотел бы отправить эти данные в виде ссылки на компонент Skills, где он отобразит некоторые динамические данные в зависимости от этого состояния.

Как мне это сделать? Спасибо!

(я знаю, что это не является устойчивым для большего приложения, но для этого приложения, мне просто нужно простое решение)

ответ

1

Я бы управлять государством в корневой компонент и сделать focused свойство (this.props.focused) во всех компонентах, в которых вы нуждаетесь. Где теперь делать setState вы вызываете функцию обратного вызова, например, так:

this.props.onFocusChanged(index) 

Вы даете эту функцию обратного вызова в качестве свойства к посадке, и в Landing вы даете его как свойство к SocialMenu. Ваше приложение будет выглядеть примерно так:

App = React.createClass({ 

    getInitialState: function(){ 
     return { focused: 0 }; 
    }, 

    clicked: (index) => { 
     this.setState({focused: index}); 
    }, 

    render() { 
     return (

      <div> 
      <Landing onFocusChanged={this.clicked} focused={this.state.focused} /> 
      <Description /> 
      <Skills focused={this.state.focused}/> 
      </div> 

    ); 
    } 
}); 
+0

как я преодолеть разрыв между SocialMenu и Landing (Social Menu является дочерним Landing, и где событие щелчка происходит)? – user1072337

+0

Так же: '' или передать все реквизиты через (es6 way): '' –

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