0
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            text: ""
        }
        this.addText = this.addText.bind(this);
    }

    addText () {
        console.log("hello");
    }
    render() {
        return(
            addButton
        )
    }
}

const addButton = <button onClick={App.addText}>Add text</button>

ReactDOM.render(<App />, document.getElementById("container"));

Когда я запускаю приложение, то функция addText не срабатывает по нажатию кнопки, в консоль ничего не выводится

1 ответ 1

0

Назови переменную с большой буквы и сделай функцией, передай в нее функцию обработчик:

const Button = (props) => <button onClick={props.onClick}>Add text</button>

В рендер выводи как JSX, и передай метод

render() {
    return <Button onClick={this.addText} />;
}

По хорошему Button должен распологатся выше над классом App

const Button = (props) => <button onClick={props.onClick}>Add text</button>

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            text: ""
        }
        this.addText = this.addText.bind(this);
    }

    addText () {
        console.log("hello");
    }

    render() {
        return <Button onClick={this.addText} />;
    }
}

ReactDOM.render(<App />, document.getElementById("container"));
3
  • То есть принцип действия примерно такой же, как если бы я создавал дочерний элемент?
    – Donut
    2 сен 2018 в 14:33
  • 1
    Это он и есть. Реакту нужно построить виртуал-дом, для этого нужны компоненты. А если тебе зачем-то нужен статический метод класс можно как-то так class App extends React.Component { static somMethod() {} } 2 сен 2018 в 15:12
  • 1
    Тогда ты сможешь его вызывать как App.someMethod(); 2 сен 2018 в 15:14

Ваш ответ

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

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