首页 > 解决方案 > 在 react native 中将 props 传递给孩子

问题描述

我有两个组件。App 组件是父组件,Btn 组件是子组件。如何从 Btn 组件更改属性文本的值?

export default class App extends Component<Props> {

  constructor() {
    super();
    this.text = 'testing';
    this.onClicked = this.onClicked.bind(this);
  }

  onClicked() {
    this.text = 'changed';
  }

  render() {
    return (
        <View style = { styles.container }>
            <Text style = { styles.welcome }> { this.text } </Text>
            <Btn />
        </View>
    );
  }
}

class Btn extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Button
        title = 'Button'
        onPress = { ? }
      />
    )
  }

}

标签: reactjsreact-native

解决方案


您可以将父组件的 onClicked 函数作为 aprop传递给子组件。

export default class App extends Component<Props> {

  ...

  render() {
    return (
        <View style = { styles.container }>
            <Text style = { styles.welcome }> { this.text } </Text>
            <Btn onClicked={this.onClicked}/>
        </View>
    );
  }
}

class Btn extends Component {

  ...

  render() {
    return (
      <Button
        title = 'Button'
        onPress = {this.props.onClicked}
      />
    )
  }

}

推荐阅读