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

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

问题描述

有没有办法只在满足特定条件时向 React 组件添加属性?

我应该在渲染后基于 Ajax 调用添加 required 和 readOnly 属性以形成元素,但我不知道如何解决这个问题,因为 readOnly="false" 不是与完全省略属性相同.

下面的例子应该可以解释我想要什么,但它不起作用.

<块引用>

(解析错误:意外的标识符)

var React = require('React');var MyOwnInput = React.createClass({渲染:函数(){返回 (<div><输入类型=文本"onChange={this.changeValue} value={this.getValue()} name={this.props.name}/>

);}});module.exports = React.createClass({getInitialState: 函数 () {返回 {是必需的:false}},componentDidMount: 函数 () {this.setState({isRequired: 真});},渲染:函数(){var isRequired = this.state.isRequired;返回 (<MyOwnInput name="test";{是必须的 ?必需":""}/>);}});

解决方案

显然,对于某些属性,React 足够智能,可以在传递给它的值不真实时省略该属性.例如:

const InputComponent = function() {const 要求 = 真;常量禁用 = 假;返回 (<输入类型=文本"disabled={disabled} required={required}/>);}

将导致:

更新:如果有人对如何/为什么发生这种情况感到好奇,您可以在 ReactDOM 的源代码中找到详细信息,特别是在行 30DOMProperty.js 文件.

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

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 doesn'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" : ""} />
        );
    }
});

解决方案

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} />
    );
}

will result in:

<input type="text" required>

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天全站免登陆