Javascript 如何动态传递道具?
我正在尝试学习如何使用react轮询(用于与后端的进一步通信,因此,我的一些代码片段已为下一步做好准备)。问题是:我希望在浏览器中看到123(如componentDidMount),但我没有 当我直接传递字符串'123'而不是Javascript 如何动态传递道具?,javascript,reactjs,react-props,Javascript,Reactjs,React Props,我正在尝试学习如何使用react轮询(用于与后端的进一步通信,因此,我的一些代码片段已为下一步做好准备)。问题是:我希望在浏览器中看到123(如componentDidMount),但我没有 当我直接传递字符串'123'而不是constpollquestion=props=>({props.quest})时它可以工作 //imports import Poll from 'react-polls'; const pollQuestion = props => (<div>
constpollquestion=props=>({props.quest})时代码>它可以工作
//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;
//导入
从“react polls”导入投票;
const pollQuestion=props=>({props.quest});
常数pollAnswers=[
{选项:“是”,投票:8},
{选项:“否”,投票数:2}
]
类扩展组件{
状态={
pollAnswers:[…pollAnswers]
}
handleVote=voteAnswer=>{
const{pollAnswers}=this.state
const newPollAnswers=pollAnswers.map(答案=>{
如果(answer.option==voteAnswer)answer.vows++
回覆
})
这是我的国家({
pollAnswers:newPollAnswers
})
}
渲染(){
const{pollAnswers}=this.state
返回(
它起作用了
);
}
};
类问题列表扩展组件{
状态={
问题:[]
}
componentDidMount(){
this.setState({questions:[{question_text:'123'}]});
}
render(){
返回(
{这个州有什么问题吗?
- {question.question_text}
)}/>
:null}
)
}
};
函数AppV(){
返回(
);
}
导出默认AppV;
问题在于您没有将this.props.quest的值传递给pollQuestion元素。要么这样做
<Poll question={this.props.quest} answers={pollAnswers} onVote={this.handleVote} />
请参见此处的代码:
还是这样做
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} />
编辑
const pollQuestion=props=>({props.quest});到
constMyPollQuestion=props=>({props.quest});
此外,所有react成分都应以大写字母开头。
React Polls question属性具有字符串的Proptype
而你是
试图传递一个元素
对它来说,这就是它不起作用的原因
直接传递问题字符串。它可以接受元素。检查这里:@DhananjaiPai您在谈论哪个组件。呈现的问题是一个,您可以传递元素,而不仅仅是strings@DhananjaiPai问题是由于prop问题,请检查proptype代码。我想你误解了这个问题。常量测试=(道具)=> {props.quest} ;