React中若想将父层Component资料传递给子层Compontent的话,唯有使用Props方法,若需要用除此之外的方式更新作为child的DOM元素的话,就可以考虑使用ref。
以下三种情况为ref建议的使用时机(参考react官网):
使用React.createRef()便可以产生ref。Ref 常常会在一个 component 被建立出来的时候,被赋值在某个实例或DOM元素的属性中,让整个Component皆可以使用该属性。以下为官网范例:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
当 ref在render中传到一个元素的时候,便可以取得ref的current参数的。
Ref 的值会根据节点的类型而有所不同:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// 产生一个可以储存 textInput DOM element 的 ref
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// 利用ref的「current」来找出DOM节点
this.textInput.current.focus();
}
render() {
// 在<input>上使用ref参数
// 和 constructor 产生的 `textInput` 连结
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
若想将上面的 CustomTextInput 包起来然後模拟它在被 mount 之後马上被点击,使用ref参数的话便可以取得CustomTextInput里的<input>
:
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focusTextInput();
}
render() {
return (
<CustomTextInput ref={this.textInput} />
);
}
}
近期说到基金理财,每次关於基金的消息上热搜,大多是基民都会心里一颤,觉得肯定基金又双叒叕跌了。确实,...
说明 说明 1.根结点中的两边固定一边大另一边小。 2.下方节点当作新的根结点,继续符合一边大一边小...
前言 React hook 是 React V16.8 新增的功能,它改变了 React 写 Cla...
一、前言 经营部落格,会是一个长期的网路事业,在初期有许多部分我认为就应该思考好,在整个经营路上才...
昨天DAY10讲了控制GPIO口来完成协议,今天来讲实际的例子,以大家最常听过三轴感测器为例,首先介...