一、 ref使用
class NoFoundPage extends Component {
methodRef: any;
objRef: any;
constructor(props) {
super(props);
this.objRef = React.createRef();
}
componentDidMount() {
console.log(this.refs.stringRef.textContent);
console.log(this.methodRef.textContent);
console.log(this.objRef.current.textContent);
}
render() {
return (
<div>
<p ref="stringRef">喜洋洋1</p>
<p ref={
e => (this.methodRef = e)}>喜洋洋2</p>
<p ref={
this.objRef}>喜洋洋3</p>
</div>
);
}
}
export default NoFoundPage;
结果如下:
二、forwardRef使用
import React from 'react';
const TargetComponent = React.forwardRef((props, ref) => (
<input type="text" ref={
ref} />
));
export default class Comp extends React.Component {
ref: any;
constructor(props: any) {
super(props);
this.ref = React.createRef();
}
componentDidMount() {
this.ref.current.value = 'please input here';
}
render() {
return <TargetComponent ref={
this.ref} />;
}
}
结果如下:
三、 context基本用法
- 之前版本的childContextType的使用
import {
Component } from 'react';
import PropTypes from 'prop-types';
// 父组件
class Parent extends Component {
state = {
childContext: '123',
};
constructor(props: any) {
super(props);
}
getChildContext() {
return {
value: this.state.childContext,