41.什么是上下文(Context)?
Context 通过组件树提供了一个传递数据的方法,从而避免了在每一个层级手动的传递props
。比如,需要在应用中许多组件需要访问登录用户信息、地区偏好、UI主题等。
// 最外层的父组件
import PropTypes from 'prop-types';
export default class Com1 extends React.Component {
constructor(props) {
super(props)
this.state = {
color: 'red'
}
}
// 1. 在父组件中定义一个function叫做getChildContext ,方法内部返回的对象就是要共享给所有子孙组件的数据
getChildContext() {
return {
color: this.state.color
}
}
// 2. 使用属性校验规定一下传递给子组件的数据类型,需要是静态方法
static childContextTypes = {
color: PropTypes.string
}
render() {
return <div>
<h1>这是 父组件 </h1>
<Com2></Com2>
</div>
}
}
// 中间的子组件
class Com2 extends React.Component {
render() {
return <div>
<h3>这是 子组件 </h3>
<Com3></Com3>
</div>
}
}
// 内部的孙子组件
import PropTypes from 'prop-types';
class Com3 extends React.Component {
// 3. 子组件在使用父组件context数据的时候首先需要对父组件传递过来的数据做类型校验
static contextTypes = {
color: PropTypes.string
}
render() {
return <div>
<h5 style={
{ color: this.context.color }}>这是 孙子组件 --- {this.context.color} </h5>
</div>
}
}
42.children 属性是什么?
Children 是一个属性(this.props.chldren
),它允许你将组件作为数据传递给其他组件,就像你使用的任何其他组件一样。在组件的开始和结束标记之间放置的组件树将作为children
属性传递给该组件。
React API 中有许多方法中提供了这个不透明数据结构的方法,包括:React.Children.map
、React.Children.forEach
、React.Children.count
、React.Children.only
、React.Children.toArray
。
const MyDiv = React.createClass({
render: function() {
return <div>{this.props.children}</div>
}
})
ReactDOM.render(
<MyDiv>
<span>{'Hello'}</span>
<span>{'World'}</span>
</MyDiv>,
node
)
43.怎样在 React 中写注释?
React/JSX 中的注释类似于 JavaScript 的多行注释,但是是用大括号括起来。
单行注释:
<div>
{/* 单行注释(在原生 JavaScript 中,单行注释用双斜杠(//)表示) */}
{`Welcome ${user}, let's play React`}
</div>
多行注释:
<div>
{/* 多行注释超过
一行 */}
{`Welcome ${user}, let's play React`}
</div>
44.构造函数使用带 props 参数的目的是什么?
在调用super()<