5
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React/React Nativeにおけるコンポーネント間での値・関数・中身の受け渡し

Posted at

基本中の基本。

値を渡す

親コンポーネント

export default class Parent extends Component {
  render() {
    return (
      <View>
        <Child text={'こんにちは'}>
      </View>
    );
  }
}

子コンポーネント

export default class Child extends Component {
  render() {
    text = this.props.text;

    return (
      <View>
        <Text>{text}</Text>
      </View>
    );
  }
}

関数を渡す

bind(this)をしないと、updateParentState内でthisが使えないので注意。

親コンポーネント

export default class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: 'ボタンを押して',
    };
  }

  updateParentState(_text) {
    this.setState({text: _text})
  }

  render() {
    return (
      <View>
        <Text>{this.state.text}</Text>
        <Child updateText={this.updateParentState.bind(this)} />
      </View>
    );
  }
}

子コンポーネント

export default class Child extends Component {
  render() {
    return (
      <View>
        <Button onPress={() => this.props.updateText('ボタンが押されました')}>
      </View>
    );
  }
}

コンポーネントがラップした中身を取得する

親コンポーネント

export default class CustomComponent extends Component {
  render() {
    return (
      <CustomView>
        <Text>中身のテキスト</Text>
      </CustomView>
    );
  }
}

子コンポーネント

export default class CustomView extends Component {
  render() {
    return (
      <View style={{flex: 1, backgroundColor: '#eee'}}>
        {this.props.children}
      </View>
    );
  }
}
5
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?