无法让 React 组件更新或传递 prop



代码所做的只是在每次单击按钮时更新计数器+1,这里的问题是当我尝试将道具计数器传递给文本时,它不会在文本组件中更新我一直在做一些研究,看起来我必须用另一个函数唤醒它, 如果有人能解释我,我将不胜感激。

import React from 'react';
import ReactDOM from 'react-dom';
class Button extends React.Component {
constructor(props) {
super(props)
this.state = {counter: 1}
}
render() {
return (
<button onClick={() => {
this.setState({
counter: this.state.counter+1
});
//tries passing  the prop counter with the state of the counter
<Text counter={this.state.counter} /> 

}}>
Click here
</button>
)
}
}
class Text extends React.Component {
render() {
return (
// returns 'clicked undefined times'
<h2 id='counter-text'>{'Clicked ' + this.props.counter + ' times'}</h2>
)
}
}
class App extends React.Component {
render() {
return (
<>
<Text/>
<Button/>
</>
)
}
}
ReactDOM.render(<App/>,document.getElementById('root'));

好吧,代码在语法上是错误的。 不能在按钮的onChange方法中呈现Text

您想要的是,当计数在按钮中更新时,它应该反映在另一个组件中,即文本。

由于这两者完全是不同的组件,因此您必须为它们提供共享状态。

为此,您可以将counter状态从Button提升到父组件App。看看这个: https://reactjs.org/docs/lifting-state-up.html

这应该有效:

import React from "react";
import ReactDOM from "react-dom";
class Button extends React.Component {
render() {
// 3. on every click, Button uses App's updater method to update the count
return <button onClick={this.props.handleCounter}>Click here</button>;
}
}
class Text extends React.Component {
render() {
return (
<h2 id="counter-text">{"Clicked " + this.props.counter + " times"}</h2>
);
}
}
// 1. Let App bear the counter state
class App extends React.Component {
constructor(props) {
super(props);
this.state = { counter: 1 };
this.handleCounter = this.handleCounter.bind(this);
}
handleCounter() {
this.setState({
counter: this.state.counter + 1
});
}
// 2. Let the Button and Text components share the App state
render() {
return (
<>
<Text counter={this.state.counter} />
<Button
counter={this.state.counter}
handleCounter={this.handleCounter}
/>
</>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));

代码的编写方式存在一些错误。 我稍微改变了它,把它放在一个你可以玩的沙盒上。

怎么了:

  • 您正在尝试<Text counter={this.state.counter} />从 在按钮的 onClick 回调中,但这永远不会 呈现时不在呈现的 return 语句内 功能。
  • 您在 Button 组件中使用状态,但文本组件不是此组件的子组件。
    • ButtonText都是App的孩子,他们都需要 以访问此计数器状态,因此应用应具有状态并通过 它作为Text的道具
    • 按钮需要回调才能更新其父 (应用) 状态。您可以将执行此操作的函数作为 prop 传递给Button,然后在onClick上调用它。

最新更新