有一些场景很适合使用refs
:
1.管理焦点,文本选择,或者媒体播放
2.触发命令性动画
3.和第三方DOM库集成
创建和访问refs的几种方法
class Login extends Component{
constructor(){
super();
this.odiv = React.createRef();
this.funcDiv = null;
}
componentWillMount(){
console.log('componentWillMount');
}
componentDidMount(){
console.log('componentDidMount');
console.log(this.refs.thisButton); //第一种方式
console.log(this.odiv.current) //第二种方式
console.log(this.funcDiv.offsetTop); //第三种方式
}
render(){
console.log('render');
let loginFlag = this.state.Loginflag;
if(loginFlag){
return <Redirect to={{pathname:'/'}} />
}
return (
<div>
{loginFlag ? "111" : "222"}
<div>
<button ref="thisButton" onClick={this.doLogin.bind(this)}>登入</button>
</div>
<div ref={this.odiv}>React.createRef </div>
<div ref={ele=>{this.funcDiv = ele;}}>react ref function </div>
</div>
)
}
}
如果ref
用在HTML元素上,构造函数中通过React.createRef()
创建的ref
会将底层DOM元素放到它的current
属性中。
如果ref
用在自定义组件类型上,ref
使用它的current
属性指向所挂载的组件实例。
功能性组件上不能使用ref
,因为它们没有实例。
//向类组件添加refs引用
class CustomTextInput extends React.component{
constructor(){
this.textInput = React.createRef();
}
focusTextInput= ()=>{
this.textInput.current.focus()
}
render(){
<input type="text" ref={this.textInput} />
<button onClick={this.focusTextInput}>获取焦点</button>
}
}
//使用了上一个组件
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focusTextInput();
}
render() {
return (
<CustomTextInput ref={this.textInput} />
);
}
}
功能性组件上不能使用ref
因为它们没有实例:
function MyFunctionalComponent() {
return <input />;
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
render() {
// 不工作!不工作!不工作!
return (
<MyFunctionalComponent ref={this.textInput} />
);
}
}
在一个功能性组件内部你可以使用ref
引用属性只要它指向一个DOM元素或者一个类组件。
function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it
let textInput = React.createRef();
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input
type="text"
ref={textInput} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
event.target event.currentTarget
1. currentTarget 返回其事件监听器触发该事件的元素。 target 返回触发此事件的元素(事件的目标节点)。
2.react添加属性必须是 data-xx 形式
<div>
outer
<p>inner</p>
</div>
<script>
if(window.addEventListeren){
div.addEventListeren('click',test)
}else{
div.attachEvent('onclick',test,false);
}
</script>
点击outer的时候 e.target e.currenttarget 其实是一样的
点击inner的时候 e.target 就是P元素 e.currentTarget就是指向div元素
但是在react中 如果在事件函数里面 吧event放在setInterval或者setTimeout里面去使用的话 event对象就是空的 ,因为他是个引用,所以在每次执行render方法的时候 都会先去把event设置为null,render执行完成之后 在重新赋值
//可以使用e.persist方法来解决上面的问题
onKeyUp={e => {
e.persist()
setTimeout(() => {
this.filterContent(e.target.value)
}, 200)
}}