【问题标题】:Non standard custom attributes in ReactJS?ReactJS 中的非标准自定义属性?
【发布时间】:2016-04-27 04:19:45
【问题描述】:

这是关于非标准属性的。 https://facebook.github.io/react/docs/tags-and-attributes.html

在反应中我已经这样做了:

 React.createElement('div', {image:'blah', etc:'blah'});

我需要在带有setAttribute 的元素上设置imageetc,并且我需要做出反应,以便在它发生变化时使用它的智能来维护它。

这里的解决方案https://stackoverflow.com/a/21654914/1828637 说要在componentDidMount 上添加它,但这不是解决方案。该属性将不会被 React 框架更改。

有没有办法告诉 react 在我的自定义标签上设置属性?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    现在可以在 react 中使用 16 个自定义属性

    // Your code:
    <div mycustomattribute="something" />
    
    // React 15 output:
    <div /> 
    
    // React 16 output:
    <div mycustomattribute="something" />
    

    react 16 custom attributes

    【讨论】:

      【解决方案2】:

      另一种选择是将属性的名称更改为 react 支持的名称(例如 data-* 属性):

      render() {
          return (
            <div data-image='blah' data-etc='blah' />
          );
      }
      

      链接到其他受支持的属性:https://facebook.github.io/react/docs/dom-elements.html

      【讨论】:

        【解决方案3】:

        此解决方案是通过使用 React 生命周期方法componentWillReceiveProps 在每次更改道具时更新 DOM 元素属性来构建链接答案。有关所有生命周期方法的更多信息,请参阅http://facebook.github.io/react/docs/component-specs.html

        (由于componentWillReceiveProps 的调用频率比实际更改时更频繁,因此您可能希望在将它们实际设置到节点上之前比较它们。)

        我提供了你可以玩的小提琴:https://jsfiddle.net/p4h267bo/,代码的相关部分摘录在这里:

        var Hello = React.createClass({
          componentDidMount() {
            this.mirrorProps(this.props);
          },
          componentWillReceiveProps(nextProps) {
            this.mirrorProps(nextProps);
          },
          mirrorProps(props) {
            var node = ReactDOM.findDOMNode(this);
            node.setAttribute('name', props.name);
          },
          render: function() {
            return <div>Hello {this.props.name}</div>;
          }
        });
        

        【讨论】:

        • 哇,非常感谢你这么快的回答,真是太棒了!效果很棒,我在你的小提琴的这个分支中将它更新为shouldMirrorProps - jsfiddle.net/Noitidart/wwLcbvfk - 你的小提琴极大地帮助了我!这是一个很好的答案,我希望我能更多地投票给你,所以我喜欢你的其他答案,并且 cmets 投票给他们。
        • 这也适用于componentWillUpdate 吗?还是componentWillUpdate只有在计算出DOM会发生变化时才调用?因为我在this.state 中有一些我想镜像为属性的东西。
        • 现在我想了想,最好在componentDidUpdate 中执行此操作,因为此时您将知道对 DOM 的任何更改都已刷新(如果您有一些条件这将导致 DOM 节点消失——当前的实现仅在节点稳定时才有效)。 Here's another fiddle!
        • 我忘了提一下,如果您正在执行任何类型的 shouldComponentUpdate 检查,您可能需要同时包含 componentWillReceivePropscomponentDidUpdate 以确保。 componentWillReceiveProps 仍然可以访问this.state,状态更新将触发componentDidUpdate
        • 除非你在setState之后使用shouldComponentUpdate来短路更新,否则React仍然会调用componentDidUpdate
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-24
        • 2011-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-07
        相关资源
        最近更新 更多