0

Пытаюсь разобраться с React.

По клике на заголовок 'Header' (в компоненте Data) вызываю функцию обработчик handler() у родителя (компонента App), и хочу поменять у родителя state. Функция отрабатывает, но state не находится. Как можно привязать state к вызову?

class Data extends React.Component{
    render(){
        return(
            <div>
            <h1 onClick={this.props.data_function}>{this.props.data_text}</h1>
            </div>
        )
    }
}


class App extends React.Component{
    constructor(){
        super();
        this.state = {in: 'Header'}
    }

    handler(){
      console.log('this.state.in', this.state.in);
      //this.setState({in: 'New_Header'});
    }

    render(){
        return(
            <Data data_text={this.state.in} data_function={this.handler} />
        )
    }
}

ReactDOM.render(
<App />, 
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">
</div>

2 ответа 2

0

Привязать можно добавив в конструкторе: this.handler = this.handler.bind(this);

В конструкторе будет так:

 constructor(){
    super();
    this.handler = this.handler.bind(this);
    this.state = {in: 'Header'}
}
0

Замените data_function={this.handler} на data_function={this.handler.bind(this)} либо в конструкторе пропишите this.handler = this.handler.bind(this)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.