【发布时间】:2018-10-21 03:28:35
【问题描述】:
我有一个带有许多子组件的 React 容器。其中一个应该是一个模式,它将向用户显示他们的名字,该名字是从父容器中的用户数据 api 中获取的。我应该能够使用道具将用户数据传递给孩子,但必须遗漏一些东西,因为显示名称不会作为值显示在输入中。
父容器
class ParentContainer extends React.Component {
constructor (props) {
super(props)
this.state = {
displayName: this.state.user.displayName
}
this.config = this.props.config
}
async componentDidMount () {
try {
const userData = await superagent.get(`/api/user`)
await this.setState({ user: userData.body })
console.log(userData.body.displayName) <===logs out user display name
} catch (err) {
console.log(`Cannot GET user.`, err)
}
}
render () {
return (
<div className='reviews-container'>
<ReviewForm
config={this.config} />
<ReviewList
reviews={reviews}
ratingIcon={this.ratingIcon}
/>
<DisplayNameModal
config={this.config}
displayName={this.displayName} />
</div>
)
}
}
export default ParentContainer
子组件
class DisplayNameModal extends React.Component {
constructor (props){
super(props)
this.state = {
displayName: this.props.displayName
}
}
render (props) {
const {contentStrings} = this.props.config
return (
<div className='display-name-container' style={{ backgroundImage: `url(${this.props.bgImgUrl})` }}>
<h2 className='heading'>{contentStrings.displayNameModal.heading}</h2>
<p>{contentStrings.displayNameModal.subHeading}</p>
<input type="text" placeholder={this.props.displayName}/>
<button
onClick={this.submitName}
className='btn btn--primary btn--md'>
<span>{contentStrings.displayNameModal.button}</span>
</button>
<p>{contentStrings.displayNameModal.cancel}</p>
</div>
)
}
}
export default DisplayNameModal
【问题讨论】:
-
您没有正确调用 state。使用这个 sn-p 更改您的代码。
-
@IhorLavs - 我现在使用
this.state.displayname传递 displayName,但是如何在子组件中使用它? -
在您的子组件中,您只需将其称为 this.props.displayName。
-
@IhorLavs - 嗯,我已经设置好了
<input type="text" placeholder={this.props.displayName}/>,但它没有显示在输入字段中。 -
控制台有错误吗?
标签: reactjs