在React.js中使用原型
道具的使用可确保在组件上接收道具的类型安全,还有助于进行正确的计算。
示例 -如果我们以字符串形式接收名称,以数字形式接收年龄,则应以相同的类型接收它。如果我们以字符串形式接收年龄,则可能导致计算错误。
要使用原型,我们必须安装以下软件包。
npm install –save prop-types
这个包由ReactTeam提供。要在组件上使用它,我们将首先导入它
import PropType from ‘prop-types’;
我们可以在任何类型的组件(有状态或无状态)上使用它。
在导出组件的末尾,我们将其写为-
Player.propTypes={};
Note the propType on name of component as shown above.
Player.propTypes={
age:PropType.number,
name:PropType.string
}使用JavaScript对象,我们可以指定prop的名称及其有效的数据类型。如果传递的数据类型不正确,我们将在浏览器控制台中收到警告。
可用的道具类型为-
any=>它可以是任何类型
Boolean
String
Number
func=>meansfunction
array
object
symbol
如果道具类型不匹配,则在浏览器控制台中显示警告消息将有助于开发人员更正错误。
尽管我们可以在每个组件上使用proptype,但是如果该组件将由其他开发人员使用并且应该大量使用数据类型,则应使用proptype。
使用引用
我们可以通过使用ref来控制dom元素。
<input value={this.props.name}
ref={(myInput)=>{this.testInput=myInput}}/>
we can use it on componentDidMount
componentDidMount(){
this.testInput.focus();
}使用Ref的替代最新方法
Inside constructor we can create a ref
constructor(props){
super(props);
this.testInputRef=React.createRef();
}我们可以在输入元素上使用创建的ref,如下所示:
<input value={this.props.name}
ref={this.testInputRef }/>如何在componentDidMount中访问这种新方式
componentDidMount(){
this.testInputRef.current.focus();
}我们必须使用ref元素上的当前函数来使它正常工作。
这样我们就可以避免创建匿名函数来创建输入引用。
使用挂钩在功能组件中创建引用
We can create ref using useRef
import React, { useRef} from ‘react’;
const myFunction=(props)=>{
const inputRef = useRef(null);//我们可以使用其构造函数为ref提供一些值
}我们可以使用类似于之前在有状态组件中创建的ref。
请注意,此引用不应立即使用,因为届时将无法准备jsx代码。
我们可以在useEffect中使用ref元素。useEffect函数在呈现jsx代码之后运行,因此我们可以确保将ref变量附加到实际元素上并可以使用。
这些引用将像上面一样使用current关键字进行访问。
This.inputRef.current.click();
通过创建ref,我们在组件中保留了一个可变字段以轻松处理它。
请注意,更改ref不会触发重新渲染。有一个useCallback方法可以通知更改并异步工作。