react面试题:
1.props、setState、this.forceupdate()会引起rerender
2.ReferenceError: must call super constructor in derived class before accessing ‘this’
class Example extends Component {
constructor(props) {
super(props); // 这句访问this
this.state = {};
}
}
3.const [count, setCount] = useState(0)是数组解耦array destructuring
4.what value of button will allow you to pass the name of the person to be hugged?
export default class About extends Component {
hug(name) {
console.log(name + 1);
}
render() {
let name = ‘dhk’
return (
6.选2
7.react createPortal(第一个参数是要渲染的组件,第二个参数是要渲染dom的位置),选4
8.React.createElement(tagName, props, childContents)
React.createElement(
type,
[props],
[…children]
)
第一个参数是必填,传入的是似HTML标签名称,eg: ul, li
第二个参数是选填,表示的是属性,eg: className,按钮点击时间,id
第三个参数是选填, 子节点,eg: 要显示的文本内容
其他用法:
React.createElement(‘li’, {
onClick:()=>{
console.log(‘createElement First Text Content’)
}
}, ‘First Text Content’),
嵌套写法:
var child1 = React.createElement('li', null, 'one');
var child2 = React.createElement('li', null, 'two');
var content = React.createElement('ul', { className: 'teststyle' }, child1, child2); // 第三个参数可以分开也可以写成一个数组
ReactDOM.render(
content,
document.getElementById('example')
);
import React,{Component} from 'react';
class ErrorBoundary extends Component{
constructor(props){
super(props);
this.state = {}
}
componentDidCatch(error,info){
this.setState({
error: error,
errorInfo: info
})
}
render(){
if(this.state.errorInfo){
return Something went wrong.
}
return this.props.children;
}
}
export default ErrorBoundary;
使用
render() {
let name = 'dhk'
const MyComponent =({children}) => ({children.length}
)
return (
<>
hello
goodbye
>
)
}
12 dangerouslySetInnerHTML虚拟dom中,不检查这个节点的children内容,因此性能会有提升。
相当于vue的v-html
function App(){
return(
红色'
}}
>
);
}
ReactDOM.render( , document.querySelector("#root"));
fallback属性接受任何在组件加载过程中你想展示的 React 元素
react.memo
const memo = (props) => React.memo(Mycomponent, (prevProps, nextProps) =>
prevProps.name === nextProps.name
)
第一个参数Mycomponent是函数式组件,第二个参数是判断Mycomponent是否根据当前传入的props有没有改变的回调函数,返回true则props没有发生改变,所以不用rerender
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
Loading... }>
22
wrap the object in parentheses圆括号