【问题标题】:How to pass a function instead of string as a prop to a component如何将函数而不是字符串作为道具传递给组件
【发布时间】:2018-03-29 01:31:03
【问题描述】:

我对 reactjs 很陌生,我一直在寻找一种简单的方法来根据状态更改按钮的颜色。基本上我正在使用 reactstrap 并且我有一个按钮,我希望它的颜色是“次要”、“危险”或“主要”按钮标签的工作方式:

<Button color={String} />

我想用一个函数把一个字符串放在那里。基本上这里是一个小功能:

buttonClassName(radioId) {
    if (this.state.whatevs.valid === false)
        return "danger";
    if (this.state.whatevs.value === radioId)
        return "primary";
    return "secondary;
}

这是我想使用它的方式:

<Button outline color={() => this.buttonClassName(1)}>blah blah1</Button>
<Button outline color={() => this.buttonClassName(2)}>blah blah2</Button>
<Button outline color={() => this.buttonClassName(3)}>blah blah3</Button>

等更多按钮,问题是,逻辑反应对我吠叫,因为:

Warning: Failed prop type: Invalid prop `color` of type `function` supplied to `Button`, expected `string`.

我同意,但是如何在不传递函数的情况下更改字符串,我是否必须从中创建状态,这似乎很无聊。当我只有两个状态时,我可以做这样的事情:

<Button outline color={(whatevs.valid === false)?"danger":"secondary"}>blah blah1</Button>

这也不是一个真正的字符串,但它有效。

【问题讨论】:

  • color={() =&gt; this.buttonClassName(1)}更改为color={this.buttonClassName(1)}

标签: reactjs


【解决方案1】:

您可以最明确地使用函数来返回字符串。您的实现的问题是您通过引用传递了一个整个函数,而不是一个函数的结果

只需在下面执行此简单修复即可。这将执行函数并将所需的字符串返回给&lt;Button&gt; 组件。

<Button outline color={this.buttonClassName(1)}>blah blah1</Button>
<Button outline color={this.buttonClassName(2)}>blah blah2</Button>
<Button outline color={this.buttonClassName(3)}>blah blah3</Button>

【讨论】:

  • 我可能有一个更大的问题来理解反应,我的印象是我必须使用类似的东西:“this.buttonClassName = this.buttonClassName(this)”才能从内部访问状态功能。所以只要我有这个,你的解决方案就行不通,既然我评论了那行,它就行了。
猜你喜欢
  • 2018-08-26
  • 2019-07-03
  • 2020-01-02
  • 2017-10-31
  • 2011-08-22
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多