将道具传递给孩子以反应当地人

时间:2018-07-27 22:34:07

标签: reactjs react-native

我有两个组成部分。 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 = { ? }
      />
    )
  }

}

2 个答案:

答案 0 :(得分:1)

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

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}
      />
    )
  }

}

答案 1 :(得分:0)

您将text的值保存在错误的位置。将其保持在您的状态。 constructor在初始渲染中运行一次,并且不会像这样再次运行。但是,作为一种React方法,如果您将数据保持在自己的状态,则只要状态发生变化,组件就会重新呈现,并且您会看到更新的数据。

然后,您可以将onClick处理程序传递给子组件,并在其中使用它。这是工作片段。我使用了class-fields,因此无需编写构造函数和箭头函数(无需绑定它)。

class App extends React.Component {
  state = {
    text: "",
  }
  
  onClick = () =>
    this.setState({text: "foo bar" });

  
  render() {
    return (
        <div>
            <p>Text is now: { this.state.text } </p>
            <Btn onClick={this.onClick} />
        </div>
    );
  }
}

const Btn = ( props ) => (
      <button onClick={props.onClick}>Click</button>
)


ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

相关问题