React基础知识

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}
      />
    );
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值