【问题标题】:How to pass a prop to a child component that is a function?如何将道具传递给作为函数的子组件?
【发布时间】:2017-10-31 16:56:44
【问题描述】:

给定:

Welcome.js

import React from 'react';
import WorkPlacePage from '../../components/welcome/WorkPlacePage';
import SkillPage from '../../components/welcome/SkillPage';

class Welcome extends React.Component {

  constructor(props) {
    super(props);
    switch (props.match.params.welcomeId) {
      case "workplace":
        this.state = { step: 1 };
        break;
      case "skills":
        this.state = { step: 2 };
        break;
      default:
        this.state = { step: 1 };
        break;
    }
    console.log(this.state)
  }

  nextStep(props) {
    console.log('nextStep')
    console.log(this)
    this.setState({
      step : this.state.step + 1
    })
  }

  showStep(props) {
    const {history} = this.props

    switch (this.state.step) {
      case 1:
        return <WorkPlacePage history={history}
                              nextStep={this.nextStep} />
      case 2:
        return <SkillPage history={history}
                          nextStep={this.nextStep} />
      default:
        return (
          <div>
            <h1>Case: Default</h1>
          </div>
        );
    }
  }

  render() {
    var style = {
      width : (this.state.step / 4 * 100) + '%'
    }
    return (
      <main>
        <span className="progress-step">Step {this.state.step}</span>
        <progress className="progress" style={style}></progress>
        {this.showStep()}
      </main>
    )
  }
}



export default Welcome;

WorkPlacePage.js

import React from 'react';
import createBrowserHistory from 'history/createBrowserHistory';

class WorkPlacePage extends React.Component {

  saveAndContinue = (e) => {
    //e.preventDefault()
    this.props.nextStep()
  }

  render() {

    const history = createBrowserHistory();

    return (
      <div>
        <h1>Workplace</h1>
        <span>
        survey things
        // <button onClick={() => history.push('/welcome/skills')}>next page</button>
        </span>

        <button onClick={() => this.saveAndContinue() }>XXX page</button>

      </div>
    );
  }
}

export default WorkPlacePage;

当我点击该按钮时,我收到以下this.props.nextStep() 的错误

Uncaught TypeError: Cannot read property 'props' of null

我做错了什么?

【问题讨论】:

    标签: reactjs react-router react-redux react-router-redux


    【解决方案1】:

    这里你需要bind上下文。否则 React 无法识别它。在这里,我以现在可以使用的方式更改了代码。

    import React, { Component } from 'react';
    import WorkPlacePage from './WorkPlacePage'
    
    class Welcome extends Component {
      nextStep() {
          console.log('Next Step callback is invoked !');
      }
    
      render(){
        return <WorkPlacePage nextStep={this.nextStep.bind(this)} />
      }
    }
    
    export default Welcome
    
    
    
    import React, { Component } from 'react';
    
        class WorkPlacePage extends Component {
          saveAndContinue() {
            console.log('Invoking function passed from the parent');
            this.props.nextStep()
          }
    
          render() {
            return (
              <div>
                <button onClick={ this.saveAndContinue.bind(this) }>Save and Continue</button>
              </div>
            );
          }
        }
    
        export default WorkPlacePage
    

    希望这会有所帮助。快乐编码!

    【讨论】:

    • 这非常有帮助 - 谢谢!
    【解决方案2】:

    您需要将组件的this 绑定到您的函数。

    您可以使用 ES6 粗箭头语法:

    saveAndContinue = (e) => {
      e.preventDefault()
      this.props.nextStep()
    }
    

    或者你可以在构造函数中绑定它:

    constructor(props) {
      super(props);
      this.saveAndContinue = this.saveAndContinue.bind(this);
    }
    

    编辑:回答您剩余的错误:

    任何时候你在函数中使用this.propsthis.state,你必须确保你是从组件绑定this

    因此,在您的 Welcome.js 中,将您的 nextStepshowStep 函数更改为使用 ES6 粗箭头语法。

    关于Uncaught TypeError: Cannot read property 'preventDefault' of undefined 的错误,那是因为您没有将事件传递给您的函数。因此,您需要进行以下更改:

    &lt;button onClick={() =&gt; this.saveAndContinue() }&gt;XXX page&lt;/button&gt;

    改为:

    &lt;button onClick={ (e) =&gt; this.saveAndContinue(e) }&gt;XXX page&lt;/button&gt;

    【讨论】:

    • 谢谢,ES6版本点击按钮报错:Uncaught TypeError: Cannot read property 'preventDefault' of undefined
    • 如果我注释掉 e.preventDefault() saveAndContinue 正在调用 nextStep() 但 nextStep() 在 w this.state 中未定义
    • 我刚刚添加了 nextStep() 函数,这在this.state 上出错,控制台说它是未定义的。想法?谢谢
    • 您可能有更多的绑定问题。您可以编辑您的原始帖子以包含完整的组件吗?
    • 更新为包含完整组件。这有帮助吗?谢谢!
    猜你喜欢
    • 2019-07-03
    • 2022-01-24
    • 2021-05-26
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    相关资源
    最近更新 更多