Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
67
Help us understand the problem. What is going on with this article?
@w-tdon

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

More than 3 years have 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で関数を渡すことで子のコンポーネントから
その関数を実行できるようになります。

67
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  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
w-tdon
フロントエンドエンジニア 勉強中

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
67
Help us understand the problem. What is going on with this article?