如何从 ref 选择器操作属性
How to manipulate attributes from ref selector
我想向具有 ref="formButton"
的元素添加一个 disabled
属性,我试过了,但似乎没有用:
React.findDOMNode(this.refs.formButton).attr('disabled')
this.refs.formButton.attr('disabled')
为此使用标准 DOM API,例如:
React.findDOMNode(this.refs.formButton).setAttribute('disabled', true)
或者,如果您想使用 jquery:
$(React.findDOMNode(this.refs.formButton)).attr('disabled')
'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>
);
}
});
请注意,您不再需要 ref
,因为您不需要从 render
方法外部访问 DOM 节点。
请参阅 React.js 文档中的 Thinking in React,了解有关组件状态中应存储的内容以及应作为属性传递的内容的更多信息。
For those reading in 2020 and later
Since the introduction of the Hooks API in React, you can rewrite the example here using a functional component.
const myComponent = () => {
const [disabled, setDisabled] = React.useState(false)
return (
<button
disabled={disabled}
onClick={() => setDisabled(true)}>
Disable
</button>
)
}
我想向具有 ref="formButton"
的元素添加一个 disabled
属性,我试过了,但似乎没有用:
React.findDOMNode(this.refs.formButton).attr('disabled')
this.refs.formButton.attr('disabled')
为此使用标准 DOM API,例如:
React.findDOMNode(this.refs.formButton).setAttribute('disabled', true)
或者,如果您想使用 jquery:
$(React.findDOMNode(this.refs.formButton)).attr('disabled')
'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>
);
}
});
请注意,您不再需要 ref
,因为您不需要从 render
方法外部访问 DOM 节点。
请参阅 React.js 文档中的 Thinking in React,了解有关组件状态中应存储的内容以及应作为属性传递的内容的更多信息。
For those reading in 2020 and later
Since the introduction of the Hooks API in React, you can rewrite the example here using a functional component.
const myComponent = () => { const [disabled, setDisabled] = React.useState(false) return ( <button disabled={disabled} onClick={() => setDisabled(true)}> Disable </button> ) }