如何动态传递道具?

How to pass the props dynamically?

我正在尝试学习如何使用 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 组件都应以大写字母开头。

React-Polls question attribute has Proptype of string

而你是

trying to pass a React Element

这就是它不起作用的原因。

直接给你问题字符串。