【问题标题】:Problem passing down function as a prop in ReactJs在 ReactJs 中将函数作为道具传递的问题
【发布时间】:2018-09-18 13:47:48
【问题描述】:
class ReturnTempPassword extends React.Component {
  constructor(props) {
    super(props);

    console.log(JSON.stringify(this.props));

  }

  render() {
    return (
        <div>
            { /* change code below this line */ }
            <p>Your temporary password is: <strong>{}</strong></p>
            { /* change code above this line */ }
        </div>
    );
  }
};

class ResetPassword extends React.Component {
  constructor(props) {
    super(props);
    this.pwdGen = this.pwdGen.bind(this);
  }

  // returns a random string as password
  pwdGen(m){
    var m = m || 9, str="",  r = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';;
    for(var i=0; i<m; i++) {
      str+= r.charAt(Math.floor(Math.random()*r.length));
    }
    return str;
  }
  render() {
    return (
        <div>
          <h2>Reset Password</h2>
          <h3>We've generated a new temporary password for you.</h3>
          <h3>Please reset this password from your account settings ASAP.</h3>
          { /* change code below this line */ }
          <ReturnTempPassword data={"data"} pass={this.pwdGen} /> 
          { /* change code above this line */ } 
        </div>
    );
  }
}; 

我正在以prop 的形式发送一个函数,并希望在子组件ReturnTempPassword 中访问它。但是data 可以作为道具使用,而不是pass。不知道我做错了什么?

仅供参考,这是一个 freecodecamp 任务,我正在尝试以自己的方式解决。 任务链接是here:

请帮我改正错误。

【问题讨论】:

  • 我可以提供解决方案,但不知道方便吗?
  • 这段代码没有错。 JSON.stringify(this.props) 不会在 props 中显示回调函数,因为函数不是 JSON 值 json.org/value.gif。只要尝试使用this.props.pass() 在任何你想要的地方实现回调函数就可以了。
  • @Kumar 感谢您指点那位朋友。这对我来说是很好的信息。

标签: javascript reactjs user-interface web-applications functional-programming


【解决方案1】:

你做的一切都是正确的 添加调用你的函数

class ReturnTempPassword extends React.Component {
  constructor(props) {
super(props);

console.log(JSON.stringify(this.props));

}

 render() {
return (
    <div>
        { /* change code below this line */ }
        <p>Your temporary password is: <strong>{this.props.pass(5)}</strong></p>
        { /* change code above this line */ }
    </div>
);
 }
 };

class ResetPassword extends React.Component {
constructor(props) {
super(props);
}

 // returns a random string as password
  pwdGen(m){
var m = m || 9, str="",  r = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';;
for(var i=0; i<m; i++) {
  str+= r.charAt(Math.floor(Math.random()*r.length));
}
return str;
}
  render() {
    return (
    <div>
      <h2>Reset Password</h2>
      <h3>We've generated a new temporary password for you.</h3>
      <h3>Please reset this password from your account settings ASAP.</h3>
      { /* change code below this line */ }
      <ReturnTempPassword data={"data"} pass={this.pwdGen} /> 
      { /* change code above this line */ } 
    </div>
  );
}

};

这个代码 this.pwdGen = this.pwdGen.bind(this);不需要

【讨论】:

  • 感谢提及。我尝试使用 bind 语句进行检查,它也适用于该语句。你能告诉我为什么不需要bind吗??
  • @VigneshSharma 如果您打算在方法中使用this,则只需将this 绑定到方法,例如:this.setState()。通过绑定this,它引用类及其属性/方法:ResetPassword。你的函数没有使用this,所以你不需要绑定它。
【解决方案2】:

更新由于其他人提供了解决方案,我可以提供我的:)

实际上,在任务中,他们不希望您创建随机密码文本。他们只是希望你传递一个名为tempPassword 的“文本”作为道具。你想在这里使用一个函数。这没关系,但如果它通过测试,我不会。

您可以通过两种方式使用此功能。

  1. 您可以将其作为道具传递给孩子。
  2. 您可以直接在父级中使用它。

您有什么特别的原因要在孩子身上使用吗?我想,没有。

所以你可以像这样在父级中使用它:

<ReturnTempPassword pass={this.pwdGen()} />

在孩子身上:

<p>Your temporary password is: <strong>{this.props.pass}</strong></p>

正如您所见,您可以在不将函数传递给子组件的情况下执行此操作。此外,您不需要绑定该函数,因为它在这里没有使用this,也没有通过回调调用它。它只是一个简单的方法,也可以与您的课程完全分开。

我在下面提供了一个类似的示例。您不需要在此处将函数作为道具传递。这样,您可以在任何地方使用它。例如,您可以将此函数放在一个文件中,然后将其导出。当您需要它时,您可以轻松地将其导入任何地方。这个函数不需要属于类本身。

但是,如果您想将其作为道具传递,@mariamelior 的回答会告诉您如何做到这一点。

// returns a random string as password
function pwdGen(m) {
  var m = m || 9,
    str = "",
    r = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (var i = 0; i < m; i++) {
    str += r.charAt(Math.floor(Math.random() * r.length));
  }
  return str;
}

class ReturnTempPassword extends React.Component {
  render() {
    return (
      <div>
        {/* change code below this line */}
        <p>
          Your temporary password is: <strong>{this.props.pass}</strong>
        </p>
        {/* change code above this line */}
      </div>
    );
  }
}

class ResetPassword extends React.Component {
  render() {
    return (
      <div>
        <h2>Reset Password</h2>
        <h3>We've generated a new temporary password for you.</h3>
        <h3>Please reset this password from your account settings ASAP.</h3>
        {/* change code below this line */}
        <ReturnTempPassword data={"data"} pass={pwdGen()} />
        {/* change code above this line */}
      </div>
    );
  }
}

ReactDOM.render(<ResetPassword />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

【讨论】:

  • 感谢您的意见。但是,我真的很想把它作为道具传递给孩子。没有具体原因,但想这样做:)
  • 有时你会这样做,有时你不会。这是你不知道的:) 我知道你只是在测试它,玩 React 但是当你学习一些东西时,然后学习正确的方法。你的功能与你的孩子无关,实际上,它与你的父母无关,也。这只是一个简单的功能。因此,将其作为道具传递在这里并不意味着任何事情。您已经问过其中一个答案的评论,为什么不需要绑定。我试图在我的回答中解释它,但这是它不应该成为道具的原因之一:) 你将使用函数作为你孩子的道具,但不像这个。
  • 好的,谢谢。您如何建议我控制子组件的密码长度?我的想法是从子组件中的文本输入元素中获取数字,然后在使用 prop 调用函数时将其作为参数传递。
  • 不客气。尽量不要在一篇文章中提出多个问题。在此处接受其中一个答案,然后针对此问题提出另一个问题,并将您到目前为止尝试过的代码添加到您的问题中。
猜你喜欢
  • 2019-11-13
  • 1970-01-01
  • 2020-11-19
  • 2021-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2019-11-05
相关资源
最近更新 更多