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

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

问题描述

如果满足某个条件,是否只能向React组件添加属性?

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

我应该为表单元素添加required和readOnly属性基于渲染后的ajax调用,但我看不出如何解决这个问题,因为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 wont 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:

var InputComponent = React.createClass({
    render: function() {
        var required = true;
        var disabled = false;

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

将导致:

<input type="text" required data-reactid=".0.0">

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

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