zoukankan      html  css  js  c++  java
  • 【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

  • 相关阅读:
    PL/SQL基础
    Oracle数据库安装与卸载
    数据结构与算法学习(四):树
    数据结构与算法学习(三):算法经典问题
    数据结构与算法学习(二):栈和队列
    数据结构与算法学习(一):线性表
    NodeJS+axios上传图片
    WCF可靠性会话之服务分流
    MVC的局部视图传参的小技巧--见人才网头部导航
    MVC分层处理
  • 原文地址:https://www.cnblogs.com/leftstan/p/15048412.html
Copyright © 2011-2022 走看看