簡體   English   中英

如何動態傳遞道具?

[英]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-Poll 問題屬性的 Proptype 為字符串

你是

試圖傳遞一個 React 元素

對它來說,這就是它不起作用的原因。

直接將問題字符串傳遞給您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM