react面试题(1)

React面试题(1)

react面试题 记录一下,大佬请移步。有问题请留言。

react中的key的作用

key是react渲染页面时react diff 用于追踪那些列表中元素被修改、被删除、被添加的辅助标识,
减少不必要的元素被重渲染

this.setState的第二个参数传入函数起到了什么作用?

this.setState((state,props)=>{
	//state-- 之前的state
	//props 当前的props 或者其他的参数
	//更新state时 是合并更新的
	//在事件处理中 setState是异步的,避免了同一个setState不会被渲染两次,
	//等待浏览器事件执行完再统一渲染
},()=>{
	//在组件开始重新渲染时调用,可以用来判断组件是否渲染完成
})

react中refs的作用?

react 中的ref 类似于 vue 中的 $ref 都可以用来获取组件的DOM元素
在react calss组件中 使用 React.createRef() 创建一个能够通过 ref 属性附加到 React 元素的 ref
通过 <div ref={ref}>子组件</div> 绑定
ref.current 指向 'div' 组件,可调用div中的属性和方法
react Hook 
const ref=useRef() 是函数组件中创建ref的方法==React.createRef(),同样用current调用子组件的属性和方法
ref转发:
class box extends React.component{
	constructor(props){
		super(props);
		this.state={
		value:'按钮'
		};
		
		this.ButtonRef=React.createRef();
	}
	componentDidMount(){
		console.log( this.inputRef.current.focus(););//可以获取input的DOM元素
	}
	render(){
		return {
			<ForwardRef ref={this.ButtonRef} text={this.state.value}><ForwardRef/>
		}
	}
	
}
const forwardRef=React.forwardRef((props,ref)=>{
//第二个参数 ref 只在使用 React.forwardRef 定义组件时存在。常规函数和 class 组件不接收 ref 参数,且 props 中也不存在 ref;
	handleButton(){
		console.log('点击了')
	}
	return (
		{
			<input type='text' ref={ref}/>
			<button>{props.value}</button>
		}
	)
})


//回调Refs + 转发ref
function CustomTextInput(props) {
  return (
    <div>
    //将ref传递到input
      <input ref={props.inputRef} type='text'/>
    </div>
  );
}

class Parent extends React.Component {
	constructor(props){
		super(props);
		this.inputElemet=null;
	}
	componentDidMount(){
	this.inputElemet.focus()
	}
  render() {
    return (
    //使用 `ref` 的回调函数将 text 输入框 DOM 节点的引用存储到 React
      <CustomTextInput
        inputRef={el => this.inputElement = el}
      />
    );
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值