在 JSX 中使用属性的布尔值

Using boolean-value of attributes in JSX

我有一个 React.js 项目。我想使用需要这种输入属性样式的数据选择器插件:

<input data-enable-time=true />

但是当 true 没有引号时,webpack 不会编译应用程序。插件不起作用,当带有引号时。 我该怎么办?

UPD.

是的,我在 componentDidMount() 中 运行 选择器 它有效,但只显示日期,没有时间。

import React, {Component} from 'react'
const Flatpickr = require('flatpickr');

export default class Date extends Component {

  componentDidMount() {
    let dateInput = document.getElementById('fPicker');
    //init picker
    new Flatpickr(dateInput);

  }

  render() {
    return(
      <div className="dateInputContainer">
        <input id="fPicker" className="flatpickr" data-enable-time="true" />
     </div>
    )
  }
}

但是data-enable-time="true"不起作用。

尝试这样的事情:

<input data-enable-time={true} />

我猜这是加载程序问题, 尝试把

  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-object-assign', 'transform-class-properties', 'transform-decorators-legacy', 'transform-es2015-modules-commonjs-simple',],
        },


      },
      ...
    ],

  },

进入您的 webpack.conf.js 文件 并通过 npm

安装每个插件

例如:

npm install --save-dev babel-plugin-react-html-attrs

根据 HTML 规范,data-enable-item=truedata-enable-item="true" 之间没有区别。它们在浏览器中的功能完全相同。因为 HTML 不带引号的属性实际上从未使用过并且会导致许多问题,所以 React 总是使用带引号的属性。

在下面的代码片段中,您可以检查它们是否确实具有完全相同的效果。

我怀疑你的插件不工作可能是因为你以错误的方式加载了你的插件,而不是因为数据属性样式。您确定仅在安装组件后才启动日期选择器(例如,在 componentDidMount 中)吗?

var withoutQuotes = document.getElementById('input-no-attribute-quotes');
var withQuotes = document.getElementById('input-with-attribute-quotes');

console.log('Are the data attributes for test exactly the same? ' + (withoutQuotes.dataset.test === withQuotes.dataset.test ? 'Yes.' : 'No.'));
console.log('Data attributes without quotes\n', withoutQuotes.dataset);
console.log('Data attributes with quotes\n', withQuotes.dataset);
<input id=input-no-attribute-quotes data-test=true />
<input id="input-with-attribute-quotes" data-test="true" />

你可以省略赋值;默认情况下,该属性将被分配一个值 true

而不是执行以下任何操作:

<input data-enable-time=true />
<input data-enable-time='true' />
<input data-enable-time={true} />

做:

<input data-enable-time />

当通过 eslint-plugin-react. (See: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md)

检测代码时,此方法避免了警告 Value must be omitted for boolean attributes [react/jsx-boolean-value]

答案就在这个github markdown。 我的解决方案是按照以下样式编写代码:

<input data-enable-time /> /*treats as true*/
<input data-enable-time={false} /> /*treats as false*/

当您要指定一个 trueish 属性时,您应该省略该值,而当您要指定它时 false 您不应该传递该属性

棘手的事情..我总是忘记这一点。 在这种情况下,只需使用: <input data-enable-time />

没有将其分配给布尔值。