I teach React.

There are two components, MainComponent and Child nested in it .... how to output data from nested in the main component?

import .......; class MainComponent extends Component { state = { mainValue: 'mainValue' }; outValues() { let inputName = this.inputName.value; let inputChild = ???????? ; console.log('ЗНАЧЕНИЕ КОМПОНЕНТА input:', inputName); console.log('ЗНАЧЕНИЕ параметра value компонента Child :', ??????? ); console.log('ЗНАЧЕНИЕ поля Child.valueAAAA компонента Child :', ??????? ); console.log('ЗНАЧЕНИЕ state.valueBBBB компонента Child :', ??????? ); } render() { return ( <div> name: <input type="text" ref={(input) => {this.inputName = input}}/> <Child ref={/* что писать сюда чтобы */} value="значение_А" onValue={this.onValueOrderStatusSelect.bind(this)}/> <button onClick={this.outValues.bind(this)}> TEST </button> </div> ); } onValueCategorySelect(e) { this.setState({mainValue: e.target.value}); } } 

and

 class Child extends Component { state = ({ valueBBBB: 'значение_valueBBBB' }) valueAAAA = 'значение_valueAAAA'; render() { let options = []; let name = "id"; this.props .categories .forEach((category,index) => { options.push( <option key={index} value={JSON.stringify(category)}>{category[name]}</option> ) }) return ( <div> <select value={this.state.value} onChange={this.props.onValue}> {options} </select> </div> ); } } 

    1 answer 1

    Good day! You can do it like this:

     <Component ref={(child) => { this._component = child; }} /> 

    In the component itself, you need a method:

     getData() { let dataToReturn; dataToReturn = что_хотите_вернуть_из_компонента; return dataToReturn; } 

    and specify in connect { withRef: true } , like this:

     export default connect(mapStateToProps, mapDispatchToProps, null, { withRef: true })(component) 

    Now everything that you return from the component is available in the parent like this:

     let componentData = this._component.getWrappedInstance().getData(); 

    But here it is worth stopping and thinking about the architecture of your application. Still, it is better to transfer the values ​​by changing the state in the stack using actions, then the behavior in general will be more predictable.