使用 reactjs 在 HTML 元素上呈现自定义属性

render custom attributes on HTML elements with reactjs

有没有办法让 reactjs 在 HTML 元素上呈现自定义属性? 我正在使用 react 使用节点 webkit 开发这个应用程序,我需要将 webkitdirectory 和 mozdirectory 属性添加到文件类型输入元素,以便能够 select 目录。

谢谢

来自 JSX Gotchas.

的自定义 HTML 属性

If you pass properties to native HTML elements that do not exist in the HTML specification, React will not render them. If you want to use a custom attribute, you should prefix it with data-.

如果您必须使用不以 data- 为前缀的属性,则必须使用组件内的 DOM API 自行添加。

giveCustomAttributes: function(input) {
  input.setAttribute('webkit-directory', '');
  input.setAttribute('moz-directory', '');
},
render: function() {
  return (
    <input type='file' ref={giveCustomAttributes} />
  );
}

如果您想要一种更具声明性的方法,您可以将此行为移动到混合中,以便在组件之间共享它。

function CustomAttrsMixin(refName, attrs) {
  return {
    componentDidMount: function() {
      var attrNames = Object.keys(attrs),
          element = this.refs[refName];

      attrNames.forEach(function(attrName) {
        element.setAttribute(attrName, attrs[attrName]);
      });
    }
  };
}

然后使用适当的值调用该函数来创建 mixin 本身。

mixins: [CustomAttrsMixin('input', {
  'webkit-directory': '',
  'moz-directory': ''
})],
render: function() {
  return (
    <input type='file' ref='input' />
  );
}

ReactJS 的 ES6 不支持 mixins。

我用这个代码

componentDidMount(){
  var input = ReactDOM.findDOMNode(this.refs.customAttributes)
  input.setAttribute('webkitdirectory', '')
  input.setAttribute('directory', '')
  input.setAttribute('multiple', '')
}

<input type='file' ref='customAttributes'/>

上传整个文件夹