Javascript 反应内联条件组件属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41798027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:38:34  来源:igfitidea点击:

React inline conditional component attribute

javascriptreactjsjsxreact-bootstrap

提问by JohnnyQ

I've been searching everywhere and can't find an answer to my question. So I want a conditional attribute which is only displayed on certain conditions, example:

我一直在到处搜索,但找不到我的问题的答案。所以我想要一个仅在某些条件下显示的条件属性,例如:

<Button {this.state.view === 'default' && 'active'}></Button>

As you can see I only want to indicate the button activeif the this.state.viewis equal to default. However, I get Unexpected token, error...

如您所见,如果等于默认值,我只想指示按钮处于活动状态this.state.view。但是,我得到Unexpected token, error...

But when I try to put an attribute before it, for example:

但是当我尝试在它之前放置一个属性时,例如:

<Button isActive={this.state.view === 'default' && 'active'}></Button>

It passes the syntax error and displays fine but this is not what I wanted to achieve.

它传递了语法错误并显示正常,但这不是我想要实现的。

How can I fix this? And what could be the reason behind it not passing?

我怎样才能解决这个问题?它没有通过的原因可能是什么?

UPDATE

更新

So I just found out that in react-bootstrapthe property activeis a shorthand of active=trueso I solved it using

所以我才发现 in react-bootstrapthe propertyactive是一个简写,active=true所以我解决了它使用

<Button active={this.state.view === 'default'}></Button>

So In case, someone encounters this problem I'm leaving it here. However, I still want to know why the conditional attribute is failing without enclosing it inside a prop-like syntax, example:

所以如果有人遇到这个问题,我就把它留在这里。但是,我仍然想知道为什么条件属性失败而不将其包含在类似 prop 的语法中,例如:

This:

这个:

active={this.state.view === 'default'}

Versus

相对

{this.state.view === 'default' && 'active'}

回答by mrlew

First of all, JSX is just a syntactic sugarfor React.createElement. So, it may look like, but, in reality, you don't specify html attributes: in fact, you are always passing props.

首先,JSX只是一个语法糖React.createElement。因此,它可能看起来像,但实际上,您没有指定html attributes:实际上,您总是通过props

For instance, the JSX code <input type="button" value="My button" />is transpiled into React.createElement('input',{type:'button',value:'My Button'}). And, when necessary, React engine renders this React Elementto the DOM as a HTML element.

例如,JSX 代码<input type="button" value="My button" />被转译为React.createElement('input',{type:'button',value:'My Button'}). 并且,在必要时,React 引擎将React Element其作为 HTML 元素呈现给 DOM。

That said, we have that JSX transpiles a propwithout a value as true(check docs). For instance: <Button active></Button>is transpiled to React.createElement(Button, { active: true });.

也就是说,我们让 JSX 将prop没有值的 a转译为true(检查文档)。例如:<Button active></Button>被转译为React.createElement(Button, { active: true });.

But, we know that HTML5 specification does not acceptattribute=true(as pointed here). For instance: <button disabled=true></button>is invalid. The correct is <button disabled></button>.

但是,我们知道 HTML5 规范不接受attribute=true(如这里所指出的)。例如:<button disabled=true></button>无效。正确的是<button disabled></button>

So, to render the HTML element to the DOM, React considers only propsthat are valid attributes(if not, the attribute is not rendered). Check all supported html attributes. And, then, finally, if it's a boolean attribute, it removes the true/falsevalue, rendering it properly.

因此,为了将 HTML 元素渲染到 DOM,React 只考虑props那些有效的attributes(如果不是,则不会渲染该属性)。检查所有支持的 html 属性。然后,最后,如果它是一个布尔属性,它会删除/值,正确呈现它。

For instance: <button active={true}></button>is transpiled to React.createElement("button", { active: true });and then React renders to the DOM <button></button>, because there is no activeattribute in HTML specification for the <button/>tag (is not in the supported attributes list).

例如:<button active={true}></button>被转译为React.createElement("button", { active: true });然后 React 渲染到 DOM <button></button>,因为activeHTML 规范中没有<button/>标签的属性(不在支持的属性列表中)。

But <button disabled={true}></button>is transpiled to React.createElement("button", { disabled: true });and React renders to the DOM <button disabled></button>.

但是<button disabled={true}></button>被转译为React.createElement("button", { disabled: true });并且 React 渲染到 DOM <button disabled></button>

I just said that to clarify your case.

我这么说是为了澄清你的情况。

You're trying to pass an activeprop to the Buttoncomponent (first letter uppercase means that's a React component: there is a React Component called Buttonhandled somewhere in your code).

您正在尝试将一个activeprop传递给Button组件(第一个字母大写表示这是一个 React 组件:Button在您的代码中某处有一个名为 handle 的 React 组件)。

That means:

这意味着:

<Button active></Button>is transpiled to React.createElement(Button, { active: true });

<Button active></Button>被转译为 React.createElement(Button, { active: true });

and

<Button active={true}></Button>is transpiled to React.createElement(Button, { active: true });

<Button active={true}></Button>被转译为 React.createElement(Button, { active: true });

The same thing!

同样的事情!

So, if you want to do a conditional prop, you can simply do something like that:

所以,如果你想做一个有条件的prop,你可以简单地做这样的事情:

<Button active={this.state.view === 'default'}></Button>

You have a condition inside brackets. Means that, if your this.state.viewis equal to default(true), activeprop will be passwed down to the component with the truevalue. If not equal, with the falsevalue.

您在括号内有一个条件。意味着,如果您this.state.view的等于default(true),则activeprop 将传递给具有该true值的组件。如果不相等,则用false值。

ButtonComponent, then, must someway handle this activeprop. It can render the buttonelement and, for instance, change it's style, pass the disabledprop... I created a fiddle to demonstrate this: https://jsfiddle.net/mrlew/5rsx40gu/

Button然后,组件必须以某种方式处理这个active道具。它可以渲染button元素,例如,改变它的样式,传递disabled道具......我创建了一个小提琴来演示这一点:https: //jsfiddle.net/mrlew/5rsx40gu/

回答by AmerllicA

Actually, I guess it is a duplicated question that I answered it in this linksometimes ago. for this specific post, there is no need condition prop for a boolean value, because it works well like below:

实际上,我想这是一个重复的问题,我有时之前在此链接中回答过。对于这个特定的帖子,布尔值不需要条件道具,因为它像下面这样工作得很好:

const { booleanValue } = this.props;
return (
    <input checked={booleanValue} />
);

Or make your own boolean value:

或者创建自己的布尔值:

const booleanValue = someThing === someOtherThing;
return (
    <input checked={booleanValue} />
);

Both of them work well, because when the booleanValueis false, reactdoesn't see the activeprop, hence it does not exist, unless you pass checkedprop to a specific component that the component will receive false checked prop from this.props.

它们都运行良好,因为当booleanValueis 时falsereact没有看到activeprop,因此它不存在,除非您将checkedprop传递给特定组件,该组件将从this.props.

But, if you wanna a have a prop on your specific component with a condition and if the condition returns false you don't want it there are two ways, I like second:

但是,如果你想在你的特定组件上有一个带有条件的道具,如果条件返回 false 你不想要它有两种方法,我喜欢第二种:

First:

第一的:

<Component someProp={condition ? yourValue : undefined} />

Second:

第二:

<Component {...(condition && { someProp: yourValue })} />

回答by Elliot

In JSX, component properties (or props) compile to a plain JavaScript object. Prop names are used as the keys of the object, and prop values are stored under those keys. The first example from the JSX docsdoes a great good job demonstrating this. In your case {view === 'default' && true}is a raw value without an associated prop name. Without a prop name to use as a key (specified by the syntax name=), JSX has nowhere to put that value in the final props object.

在 JSX 中,组件属性(或 props)编译成一个普通的 JavaScript 对象。道具名称用作对象的键,道具值存储在这些键下。JSX 文档的第一个示例很好地展示了这一点。在您的情况下,{view === 'default' && true}是一个没有关联道具名称的原始值。如果没有用作键的 prop 名称(由语法指定name=),JSX 就无法将该值放入最终的 props 对象中。

However, JSX will accept props via your original syntax if the expression inside the curly braces evaluates to an object. For example, you could do {{ active: view === "default" }}. In this case JSX can get both the key and value that it needs from the provided object, so no active=is necessary.

但是,如果花括号内的表达式计算为一个对象,JSX 将通过您的原始语法接受 props。例如,您可以执行{{ active: view === "default" }}. 在这种情况下,JSX 可以从提供的对象中获取它需要的键和值,所以没有active=必要。