React高级指南(三)【Refs and the DOM】
在常规的React数据流中,props是父组件与子组件交互的唯一方式。为了修改子元素,你需要用新的props去重新渲染子元素。然而,在少数情况下,你需要在常规数据流外强制修改子元素。被修改的子元素可以是React组件实例,也可以是DOM元素。在这种情况下,React提供了解决办法。 何时使用Refs下面有一些恰当地使用refs的场景:
如果可以通过声明式实现,就尽量避免使用refs。 例如,相比于在 为DOM元素添加RefReact支持给任何组件添加特殊属性。 当给HTML元素添加 class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focus = this.focus.bind(this);
}
focus() {
// 通过使用原生API,显式地聚焦text输入框
this.textInput.focus();
}
render() {
// 在实例中通过使用`ref`回调函数来存储text输入框的DOM元素引用(例如:this.textInput)
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={this.focus}
/>
</div>
);
}
}
React将会在组件安装( 对class设置 为类(Class)组件添加Ref为用类(class)声明的自定义组件设置 class AutoFocusTextInput extends React.Component {
componentDidMount() {
this.textInput.focus();
}
render() {
return (
<CustomTextInput
ref={(input) => { this.textInput = input; }} />
);
}
}
需要注意的是,这种方法仅对以类(class)声明的 class CustomTextInput extends React.Component {
// ...
}
Refs与函数式Components你不能在函数式组件上使用 function MyFunctionalComponent() {
return <input />;
}
class Parent extends React.Component {
render() {
// 无效!
return (
<MyFunctionalComponent
ref={(input) => { this.textInput = input; }} />
);
}
}
如果你需要使用 然而你可以在函数式组件内部使用 function CustomTextInput(props) {
// textInput must be declared here so the ref callback can refer to it
let textInput = null;
function handleClick() {
textInput.focus();
}
return (
<div>
<input
type="text"
ref={(input) => { textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
不要滥用Refs在你应用中,你可能会倾向于使用 旧版API: String类型的Refs如果你之前使用过React,你可能了解过之前的API:string类型的 注意如果 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |