gpt4 book ai didi

javascript - 如何动态传递props?

转载 作者:行者123 更新时间:2023-12-02 22:48:05 25 4
gpt4 key购买 nike

我正在尝试学习如何使用react-polls(为了与后端进一步通信,因此,我的代码的一些片段已为下一步做好准备)。问题是:我希望在浏览器中看到 123(如在 componentDidMount 中),但我没有。

当我直接传递字符串“123”而不是 const pollQuestion = props => (<div>{props.quest}</div>); 时它有效。

//imports

import Poll from 'react-polls';


const pollQuestion = props => (<div>{props.quest}</div>);

const pollAnswers = [
{ option: 'Yes', votes: 8 },
{ option: 'No', votes: 2 }
]

class PollQuestion extends Component {
state = {
pollAnswers: [...pollAnswers]
}

handleVote = voteAnswer => {
const { pollAnswers } = this.state
const newPollAnswers = pollAnswers.map(answer => {
if (answer.option === voteAnswer) answer.votes++
return answer
})
this.setState({
pollAnswers: newPollAnswers
})
}

render () {
const { pollAnswers } = this.state
return (
<div>
<Poll question={pollQuestion} answers={pollAnswers} onVote={this.handleVote} />
<p>It works</p>
</div>
);
}
};

class QuestionList extends Component {
state = {
questions: []
}

componentDidMount(){
this.setState({ questions: [{question_text:'123'}]});
}

render(){
return (
<div>{this.state.questions?
<ul>
<PollQuestion quest={this.state.questions.slice(0, 1).map(question => <li>{question.question_text}</li>)} />
</ul>:null}
</div>
)
}
};


function AppV() {
return (
<div className="App">
<QuestionList/>
</div>
);
}

export default AppV;

最佳答案

问题是您没有将 this.props.quest 的值传递给 pollQuestion 元素。要么这样做

<Poll question={this.props.quest} answers={pollAnswers} onVote={this.handleVote} />

请参阅此处的代码:https://stackblitz.com/edit/react-nngrut

或者这样做

Edit 
const pollQuestion = props => (<div>{props.quest}</div>); to
const MyPollQuestion = props => (<div>{props.quest}</div>);

<Poll question={<MyPollQuestion quest={this.props.quest} />} answers={pollAnswers} onVote={this.handleVote} />

https://stackblitz.com/edit/react-sxf2kx?file=AppV.js

此外,所有 React 组件都应以大写字母开头。

关于javascript - 如何动态传递props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58299133/

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