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

  • 相关阅读:
    Xpath语法与lxml库的用法
    Selenium--使用参考
    PhantomJS的替代品--无头浏览器(Headless Chrome)
    为什么只有一个元素的tuple要加逗号?
    反爬利器--设置代理服务器
    LeetCode 221. 最大正方形 | Python
    LeetCode 572. 另一个树的子树 | Python
    LeetCode 98. 验证二叉搜索树 | Python
    LeetCode 45. 跳跃游戏 II | Python
    LeetCode 25. K 个一组翻转链表 | Python
  • 原文地址:https://www.cnblogs.com/leftstan/p/15048412.html
Copyright © 2011-2022 走看看