Help us understand the problem. What is going on with this article?

[react]子のコンポーネントから親のstateを変更する方法

More than 1 year has passed since last update.

子のコンポーネントから親のstateを変更する方法

子のコンポーネントから親のstateを変更したい場合があると思います。
最近ここでかなり時間を取られたのでメモがわりに残しておこうと思います。

コード

  • parent(親コンポーネント)
import React from 'react';
import PropTypes from 'prop-types';
import child from './child';

class parent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      hoge: 'hogehoge'
    };
  }

  hogeFunc() {
    this.setState({ hoge: '変えたぞ' });
  }
  render() {
    return (
      <div>
        <child dataHoge={() => { this.hogeFunc(); }} />
      </div>
    );
  }
}
  • child(子コンポーネント)
import React from 'react';
import PropTypes from 'prop-types';

const propTypes = {
  dataHoge: PropTypes.func,
};

class child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  clickButton() {
    return this.props.dataHoge();
  }

  render() {
    return (
      <div>
        <button onClick={() => { this.clickButton(); }}>ボタン</button>
      </div>
    );
  }
}

child.propTypes = propTypes;
export default child;

まとめ

親のコンポーネントでsetStateさせる関数を用意させ、
子のコンポーネントにpropsで関数を渡すことで子のコンポーネントから
その関数を実行できるようになります。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away