React.Fragment
在不额外创建DOM元素的情况下,让render()方法返回多个元素
根节点可以用<React.Fragment> </React.Fragment>或简写方式 <> < />
表示
render() {
return (
<React.Fragment>
<p>Hello World</p>
</React.Fragment>
);
}
也可以使用简写语法
render() {
return (
<>
<p>Hello World</p>
< />
);
}
Refs
勿过度使用Refs
创建Refs
Refs 是使用 React.createRef() 创建的,并通过 ref 属性附加到 React 元素。
- 当 ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性。
- 在componentDidMount函数中通过访问dom让文本框处于激活状态
class Demp extends React.Component {
constructor(props) {
super(props);
// 创建一个 ref 来存储 textInput 的 DOM 元素
this.inputRef = React.createRef();
}
render() {
return <input type="text" ref={this.inputRef} />;
}
componentDidMount() {
// 直接使用原生 API 使 输入框获得焦点
// 注意:我们通过 "current" 来访问 DOM 节点
this.inputRef.current.focus();
}
}
回调Refs
React 也支持另一种设置 refs 的方式,称为“回调 refs”。
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
class Parent extends React.Component {
render() {
return (
<CustomTextInput
inputRef={el => this.inputElement = el}
/>
);
}
}