【react】原生语法——列表渲染,条件渲染,事件响应
列表渲染
使用map函数遍历数组,生成一个html列表(表头内容)
const heads = ["name", "sno", "sex", "age"]; const thead = heads.map((head) => <td key={head}> {head} </td> ); const students = [ ["doomfist", "123456", "male", "21"], ["tracer", "123457", "female", "21"], ["genji", "123458", "male", "21"], ["mercy", "123459", "female", "21"], ]
//嵌套遍历 const tstudents = students.map((stu)=> <tr key={stu}> {stu.map((info)=> <td key={info}> {info} </td> )} </tr> )
条件渲染&事件响应
MyTable组件用于展示数据
class MyTable extends React.Component { render() { return ( <table border="1"> <thead><tr>{thead}</tr></thead> <tbody> {tstudents} </tbody> </table> ); } }
一个用于切换视图的按钮(改变条件)
function ToggleButton(props){ return ( <button onClick={props.onClick}> 切换视图 </button> ); }
接着将两个组件组合在一个大的组件中
class MainBox extends React.Component { constructor(){ super(); //绑定方法 this.toggleTable = this.toggleTable.bind(this); //是否展示 this.state = {tableShow: true}; } //通过事件响应,改变tableShow的值 toggleTable(){ this.setState(prevState=>({ tableShow: !prevState.tableShow })) }
//判断是否展示,为table变量赋值是否为空 render(){ let table = null; if(this.state.tableShow){ table = <MyTable/> }; return( <div> <ToggleButton onClick={this.toggleTable}/> {table} </div> ) } }
源码:https://www.jianguoyun.com/p/DblDki8QzLDdCRi9uIUE
参考资料:https://www.runoob.com/react/react-tutorial.html