1、React.Fragment的使用
renderCompontent = () => {
return (
<div>
<Compontent1/>
<Compontent2/>
</div>
)
}
render () {
const currentCompontent= this.renderCompontent ()
return (
{currentCompontent}
)
}
尝试过就会发现以上写法会报错:报错-Objects are not valid as a React child…,若修改为以下写法就不会报错了:
renderCompontent = () => {
return (
<div>
<Compontent1/>
<Compontent2/>
</div>
)
}
render () {
const currentCompontent= this.renderCompontent ()
return (
<div>
{currentCompontent}
</div>
)
}
观察发现我们只是给render方法中的currentCompontent外部加了一对div标签,但是这时会发现多加的这一层div在渲染出来的html中并没有实际作用,有事还会影响css属性的正常继承,为了解决这一问题就用到了React.Fragment,写法如下:
renderCompontent = () => {
return (
<React.Fragment>
<Compontent1/>
<Compontent2/>
</React.Fragment>
)
}
render () {
const currentCompontent= this.renderCompontent ()
return (
<div>
{currentCompontent}
</div>
)
}
上面的方法即能解决报错也不会在渲染结果中多生成一层无用的div标签
2、React字符串变量拼接
<div style={{ flexDirection: this.state.orientation }}
className={`${'_gisTools ' + this.state.className}`} >
{this.props.children}
</div>
3、给指定类型的变量赋初始值
// 定义变量类型
interface IHistory {
key?: string
value?: string
checked?: boolean
}
// 使用类型并赋初始值
history: IHistory[] = []
// 或
interface IParam {
param : string
}
const param : IParam = {
param : key
}