如何有条件地向React组件添加属性? [英] How do I conditionally add attributes to React components?

查看:53
本文介绍了如何有条件地向React组件添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法只能在满足特定条件的情况下向React组件添加属性?

Is there a way to only add attributes to a React component if a certain condition is met?

我应该在渲染后基于Ajax调用添加必填属性和readOnly属性以形成元素,但是由于readOnly ="false"与完全省略该属性不同,因此我看不到如何解决此问题.

I'm supposed to add required and readOnly attributes to form elements based on an Ajax call after render, but I can't see how to solve this since readOnly="false" is not the same as omitting the attribute completely.

下面的示例应该解释我想要的内容,但是它不起作用(解析错误:意外的标识符).

The example below should explain what I want, but it won't work (Parse Error: Unexpected identifier).

var React = require('React');

var MyOwnInput = React.createClass({
    render: function () {
        return (
            <div>
                <input type="text" onChange={this.changeValue} value={this.getValue()} name={this.props.name}/>
            </div>
        );
    }
});

module.exports = React.createClass({
    getInitialState: function () {
        return {
            isRequired: false
        }
    },
    componentDidMount: function () {
        this.setState({
            isRequired: true
        });
    },
    render: function () {
        var isRequired = this.state.isRequired;

        return (
            <MyOwnInput name="test" {isRequired ? "required" : ""} />
        );
    }
});

推荐答案

显然,对于某些属性,如果您传递给它的值不真实,React足够聪明,可以忽略该属性.例如:

Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. For example:

const InputComponent = function() {
    const required = true;
    const disabled = false;

    return (
        <input type="text" disabled={disabled} required={required} />
    );
}

将导致:

<input type="text" required>

更新:如果有人对这种情况的发生方式/原因感到好奇,可以在ReactDOM的源代码中找到详细信息,特别是在

Update: if anyone is curious as to how/why this happens, you can find details in ReactDOM's source code, specifically at lines 30 and 167 of the DOMProperty.js file.

这篇关于如何有条件地向React组件添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆