所有代碼所做的就是在每次單擊按鈕時更新計數器 1,這里的問題是當我嘗試將道具計數器傳遞給文本時,它不會在 Text 組件中更新我一直在做一些研究看起來我必須用另一個功能喚醒它,如果有人能解釋我,我將不勝感激。
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'));
uj5u.com熱心網友回復:
好吧,代碼在語法上是錯誤的。您不能Text在onChange按鈕的方法中渲染 a 。
您想要的是,當 Button 中的計數更新時,它應該反映在另一個組件中,即 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"));
uj5u.com熱心網友回復:
您的代碼撰寫方式存在一些錯誤。我對其進行了輕微更改,并將其放在您可以玩的沙箱中。
怎么了:
- 您正在嘗試
<Text counter={this.state.counter} />從按鈕的 onClick 回呼中進行渲染,但是如果不在渲染函式的 return 陳述句中,則永遠不會渲染。 - 您在 Button 組件內部使用 state,但 Text 組件不是該組件的子組件。
- 這兩個
Button和Text是孩子App,和他們都需要訪問這個計數器狀態,所以應用程式應該具有的狀態,并把它作為道具的Text - 按鈕需要回呼才能更新其父(應用程式)狀態。您可以將執行此操作的函式作為 prop 傳遞給
Button,然后在 上呼叫它onClick。
- 這兩個
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/364490.html
標籤:javascript 节点.js 反应
