gpt4 book ai didi

javascript - 从无状态功能组件动态渲染按钮

转载 作者:行者123 更新时间:2023-11-28 14:11:29 26 4
gpt4 key购买 nike

我有无状态的功能子组件,如下所示

const MultiChoiceQuestion = props => (
<div>
<h1>{props.questionText}</h1>
<button>{props.choice}</button>
</div>
)

我希望该组件能够根据父组件中的数组动态生成按钮。

class CNA extends Component {
constructor(props) {
super(props)
this.state = {

}

const choiceArray = ['1', '2', '3']
choiceArray.map(questionChoice => {
return questionChoice
})

}
render() {
return (
<React.Fragment>
<p>This is the cna survey</p>
<MultiChoiceQuestion questionText="Hello" choice={this.questionChoice} />
</React.Fragment>
)
}

所以基本上,因为我的chooseArray中有3个项目,所以我想生成3个按钮。有什么想法吗?

最佳答案

在构造函数中,您应该将 choiceArray 定义为实例属性,而不仅仅是函数中的 var:this.choiceArray = ['1', '2', '3']

然后将map()移动到渲染函数的JSX中:

{this.choiceArray.map(questionChoice => <MultiChoiceQuestion questionText="Hello" choice={questionChoice} /> )
}

关于javascript - 从无状态功能组件动态渲染按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59278576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com