[英]React Prop rendering as object - don't understand why
我是React的新手,我只是想不出來......
我試圖將我的狀態傳遞給父組件中的prop,然后在子組件中呈現該狀態。 像這樣:
class App extends Component {
constructor(props) {
super(props);
this.state = {
text: 'hello'
}
}
render() {
return (
<div className="App">
<MessageList textProp={this.state.text}/>
</div>
);
}
}
const MessageList = textProp => {
return (
<div className='MessageList'>
{textProp}
</div>
)
}
React將無法正確呈現,聲稱它是一個試圖呈現的對象。
我可以使用{textProp.textProp}
訪問該屬性,為什么它呈現包含同名屬性的對象?
我確信這很簡單,但我可以解釋一下!
提前致謝。
組件的道具是一個對象,就像它們的狀態是一個對象一樣。 所以你想要更像的東西:
const MessageList = props => {
return (
<div className='MessageList'>
{props.textProp}
</div>
)
}
或者,使用解構:
const MessageList = ({ textProp }) => {
return (
<div className='MessageList'>
{textProp}
</div>
)
}
當您聲明無狀態組件時,您需要指定您希望它接收的參數,它可以是(props)
或({ specific })
在您的情況下:
const MessageList = ({ textProp }) => (
<div className='MessageList'>
{textProp}
</div>
);
注意我怎么做=> ()
將返回標記,你沒有做{ return () }
只是一個提示更好地運行:)
MessageList
的textProp
是父組合的props
集合。 在您的情況下,集合將只有textProp.
要完成這項工作,您需要執行以下操作。
const MessageList = ( {textProp} ) => {
return (
<div className='MessageList'>
{textProp}
</div>
)
}
要么
const MessageList = (textProp) => {
return (
<div className='MessageList'>
{textProp.textProp}
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.