[英]How to convert a React JS functional component to a class component?
嗨,我有這個reactjs
片段我需要將其轉換為class
組件(現在它是一個功能性組件)
但這必須小心執行,因為我嘗試從Form
組件獲取值到Main
組件並在Main
組件中打印該值。
這是我的Main.jsx
function Main(props) {
const [firstName, setFirstName] = React.useState('');
return (
<div>
<Form setFirstName={setFirstName} firstName={firstName} />
<p> {firstName} <p/> // this works fine
</div>
);
}
這就是我需要將其編寫為Form.jsx
組件而不是現在的functional component
的class
。
function Form({ firstName, setFirstName }) {
const handleChange = (event) => {
setFirstName(event.target.value)
}
return (
<div>
<TextField onChange={handleChange} value={firstName} />
</div>
);
}
我試圖像這樣轉換它,但是它沒有在里面打印firstName
的值
export default class Form extends Component {
constructor(props) {
super(props);
this.state = {
firstName: "",
};
this.handleChange = this.handleChange.bind(this);
}
handleChange = (event) => {
this.props.firstName = event.target.value;
};
render() {
return (
<div>
<TextField onChange={this.handleChange} value={this.state.firstName} />
</div>
);
}
}
<p> {firstName} <p/> // and now this wouldn'tt work after converting this to a class component
有人可以幫幫我嗎?
首先,我完全不明白您為什么要將其轉換為 class,但我認為您有充分的理由。
不要像這樣重新分配道具: this.props.firstName = event.target.value;
. React 中的數據流向一個方向發展。 上 -> 下。 如果你需要更新一個道具,你可以傳遞一個單獨的道具,它是一個 function 來更新第一個值(參見提升 state up的文檔)。
如果您想將 state 移動到Form
組件,只需像這樣更新 state :
handleChange = (event) => {
this.setState({ firstName: event.target.value });
};
但請注意,這不會更新道具,所以這可能不是您要找的。
為了與您的功能組件設置更相似,請不要在Form
中使用 state 並像以前一樣將其保留在Main
中。 這意味着我們也可以刪除構造函數。
export default class Form extends Component {
handleChange = (event) => {
this.props.setFirstName(event.target.value);
};
render() {
return (
<div>
<TextField onChange={this.handleChange} value={this.props.firstName} />
</div>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.