[英]React component props value issue
我目前正在學習 React,我有一個簡單的組件可以呈現簡單的純文本。 我創建了一個小組件,用於從 props 獲取簡單的純文本,但我很驚訝。 當我為變量分配一個簡單的靜態值時,它工作正常,但是當我嘗試從道具中獲取該值時,它不起作用。
這是示例代碼段。
let TextEditor = React.createClass({
getInitialState: function () {
var content = "test 2";
var content = this.props.plainText
return {
content: content
};
},
render() {
return (
<div>
<Editor
value={this.state.content}
/>
</div>
)
}
})
提前謝謝你的線索
getInitialState 現在似乎有點過時了。 我建議至少研究一下 ES6 的做事方式。 最好不要在構造函數中立即將 props 設置為 state,您可以在組件安裝后更新狀態。 還有其他方法可以將您的道具放入您的組件中,因此可以更詳細地查看 react 文檔。
作為一個基本的 ES6 示例......
class MyComp extends React.Component {
constructor(props) {
super(props);
this.state = { content: '' };
}
componentDidMount = () => {
const { plainText } = this.props;
this.setState({ content: plainText });
}
render() {
const { content } = this.state;
return (
<div>
<Editor value={content} />
</div>
);
}
}
您可以使用以下代碼來實現預期結果:
class MyComp extends React.Component {
constructor(props) {
super(props);
this.state = { content: this.props.plainText };
}
render() {
const { content } = this.state;
return (
<div>
<Editor value={content} />
</div>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.