【问题标题】:How to manipulate attributes from ref selector如何从 ref 选择器中操作属性
【发布时间】:2023-03-20 08:04:01
【问题描述】:

我想为具有ref="formButton" 的元素添加一个disabled 属性,我试过了,但它似乎不起作用:

React.findDOMNode(this.refs.formButton).attr('disabled')
this.refs.formButton.attr('disabled')

【问题讨论】:

标签: attributes reactjs selector


【解决方案1】:

为此使用标准DOM API,例如:

React.findDOMNode(this.refs.formButton).setAttribute('disabled', true)

或者,如果你想使用 jquery:

$(React.findDOMNode(this.refs.formButton)).attr('disabled')

【讨论】:

  • 这不是 React 的方式。您应该只在与外部/第 3 方(即非 React)组件/库交互时直接在 DOM 元素上设置属性。
  • 如何使用 React 组件,例如来自 material-ui 库的组件,您需要在 TextField 控件生成的输入之一上设置属性?这将如何以 React 方式完成?
【解决方案2】:

'React' 的做法是在 render 方法中控制按钮的 disabled 属性,并使用组件的状态来跟踪它。

例如:

var myComponent = React.createClass({

  getInitialState: function() {
    return { disabled: false };
  },

  disableFormButton: function() {
    this.setState({ disabled: true });
  },

  render() {
    return (
      <div>
        ...
        <button
          disabled={this.state.disabled}
          onClick={this.disableFormButton.bind(this)}>
          Disable
        </button>
      </div>
    );
  }
});

JSFiddle here

请注意,您不再需要 ref,因为您不需要从 render 方法之外访问 DOM 节点。

请参阅 React.js 文档中的 Thinking in React,了解有关组件状态中应存储什么以及应作为属性传递的更多信息。

对于那些在 2020 年及以后阅读的人

由于在 React 中引入了Hooks API,你可以使用函数式组件重写这里的示例。

const myComponent = () => {
  const [disabled, setDisabled] = React.useState(false)
  return (
    <button
      disabled={disabled}
      onClick={() => setDisabled(true)}>
        Disable
    </button>
  )
}

【讨论】:

    猜你喜欢
    • 2011-09-23
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    相关资源
    最近更新 更多