本文共 3941 字,大约阅读时间需要 13 分钟。
1 在constructor中绑定
constructor(props) { super(props); this.goBack = this.goBack.bind(this); } goBack(){ this.props.history.goBack(); }<span onClick={this.goBack}></span>
2 调用时使用箭头函数 (不推荐)
<span onClick={ ()=>{ this.goBack() }}></span> 3 在constructor中定义 constructor(props) { super(props); goBack = (e)=>{ this.props.history.goBack(); } } <span onClick={this.goBack}></span>推荐:下面这种写法不需绑定就可获得this
handleChange=(event)=>{
console.log(this);//当前的组件 }通过map:
import React from 'react'import {Link} from 'react-router-dom'class MenuHeader extends React.Component { state={ menuList:[{ID: 163, Name: "家居日用", ParentID: 0, Ord: 10,}, {ID: 386, Name: "母婴儿童", ParentID: 0, Ord: 8, Pic: "/"}, {ID: 529, Name: "生活服务", ParentID: 0, Ord: 0, Pic: "/"}, {ID: 533, Name: "超级优博", ParentID: 0, Ord: 0, Pic: "/"}, {ID: 535, Name: "美妆个护", ParentID: 0, Ord: 0, Pic: "/"} ] } render() { return () }}export default MenuHeader{this.state.menuList.map( item => (
- {item.Name}
) )}
【注意:map下,离外层最近的元素必须有key,且key的值必须唯一;否则其他情况都会报错。例如上面的,li就是离循环外层最近的,如果可以不在li上,而在link或span上,就会出现报错】
通过push return
import React from 'react'import {Link} from 'react-router-dom'class MenuHeader extends React.Component { state={ menuList:[{ID: 163, Name: "家居日用", ParentID: 0, Ord: 10,}, {ID: 386, Name: "母婴儿童", ParentID: 0, Ord: 8, Pic: "/"}, {ID: 529, Name: "生活服务", ParentID: 0, Ord: 0, Pic: "/"}, {ID: 533, Name: "超级优博", ParentID: 0, Ord: 0, Pic: "/"}, {ID: 535, Name: "美妆个护", ParentID: 0, Ord: 0, Pic: "/"} ] } getMenuList= () => { var menuList = this.state.menuList; var html=[]; for(var i = 0; i < menuList.length; i++) { html.push(
【map 渲染不出来的几种情况】
1 map语法写错,
正确的是 {dataObj.map((item,index)=>())}记住里面的都是 ()不是{},如果想用{}则里面要带一个return,例:{ this.props.listData.options.data.map((item,index)=>()) }
效果等同于下面:
{ this.props.listData.options.data.map((item,index)=>{ return () }) }
2 对象为null,报错null或者length错误;
这种情况使用条件渲染处理:import React from 'react'import {Link} from 'react-router-dom'class MenuHeader extends React.Component { state={ menuList:[] } getMenuList=(menuList)=>{ var html =[]; var menuList=menuList; menuList.map((item,index)=>{ html.push(
暂无数据
}【注意,上面的没有循环的li也是要有key,否则会报错:index.js:1446 Warning: Each child in a list should have a unique "key" prop.】
转载地址:http://lnurf.baihongyu.com/