1、使用一个父节点包裹
jsx中返回多个零散的节点时候,应该有一个父节点div包裹,如下:
rerutn(
<div>
<p>111</p>
<p>222</p>
<p>333</p>
</div>
)
2、注释
jsx 中用{/* */}的注释形式,如下例子:
return (
// jsx 外面的注释
<div>
{/* jsx 里面的注释 */}
<p>hello world</p>
</div>
)
3、样式写法
①在jsx中类名不用class,而是className,如<p className= "p1">hello world</p>
②for写为htmlFor,如<p htmlFor= "p1">hello world</p>
如果平时写html代码习惯了写class和for,可以用npm安装babel-plugin-react-html-attrs
这个插件,之后就可以正常的在JSX中使用class和for了。
③另外写内联样式的css时候,这样写<p style= {{fontSize='12px'}}>hello world</p>
样式名称用驼峰命名法
④要改变UI框架样式如ant design的css样式,可以在对应属性名前面加上:global
然后空格写样式,如:
:global .ant-col-8{
width: 100%;
}
4、事件
例如需要绑定一个click事件在p元素上的时候,这样写:
class Hello extends React.Component {
clickHandler(){
alert('123');
}
render(){
return(
<div>
<p onClick={this.clickHandler.bind(this)}>123</p>
</div>
)
}
}
5、循环
JSX中的循环用array.map的写法,例如:
class Hello extends React.Component {
render() {
const arr = [11, 22, 33];
return (
<div>
<ul>
{
arr.map((item,index)=>
<li key={index}>{item}</li>
)
}
</ul>
</div>
)
}
}
把index赋值给key,循环出来的li都是不一样的
6、判断
JSX中的判断一般用三目运算符(也叫三元运算符),放在大括号中使用,如下例:
class Hello extends React.Component {
render() {
const a = 100;
return (
<div>
<p>{a>10 ? "true" : "false"}</p>
</div>
)
}
}
7、props和state
①props
一般用于父组件给子组件传递数据,如一个页面引用了Header组件,写成<Header title="this is a title" />
。此时在Header组件中可以这样获取title值:
render(){
return(
<p>{this.props.title}</p>
)
}
②如果组件自身内部需要改变,一般用state
设置 state 的值的时候,一定要用this.setState
,不能直接赋值修改,如下例子:
class Hello extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
// 显示当前时间
now: Date.now()
}
}
render() {
return (
<div>
<p onClick={this.clickHandler.bind(this)}>
hello world{this.state.now}
</p>
</div>
)
}
clickHandler() {
this.setState({ now: Date.now() })
}
}
8、Router
需要安装react-router: npm install react-router --save
网友评论