小白文章之---React框架学习(二)

1、鼠标点击事件,通过点击一个a标签,跳转界面

{/*添加一个a标签,并定义跳转的路径,点击的方法是用来阻止事件的,*/}
<a href="https://www.baidu.com" onClick={onTouchClick}>点击</a>
{/*定义一个点击的方法,这里的preventDefault是阻止事件的默认行为,a标签就不能跳转*/}
function onTouchClick(e) {
    e.preventDefault();
}

2、条件渲染,根据属性不能,渲染不同的值
新建一个js文件,编写判断逻辑

import React from 'react';

class IfTest extends React.Component{
    constructor( props){
        super( props );
        //返回的值
        let content;
        if(this.props.age >= 18){
            content = <h1>年龄适合,可以进入</h1>
        }else{
            content = <h1>年龄不符合,不可以进入</h1>
        }
        //判断复制
        this.state = {content : content}
    }
    //返回值
    render() {
        return (
            <div>
                {this.state.content}
            </div>
        )
    }
}

export default IfTest

在App中去调用,根据定义的熟悉,传值判断,并返回值呈现在界面上

<IfTest age="15"/>

3、使用map渲染多个组件

const number = [1,2,3,4,5];
const listItems = number.map((value) => <li>{value}</li>)
<ul>{listItems}</ul>

4、表单提交input系列
创建一个js文件,在文本框中,绑定改变事件,当值改变时,将输入的值赋给定义的属性

import React from 'react';
class InputTest extends React.Component{
    constructor( props){
        super( props );
        //在构造器中定义属性
        this.state = {account:""}
    }
    //当改变时将目标的值赋值给属性
    onInputChange = (e) => {
        this.setState({account:e.target.value})
    };
    //提交按钮的事件
    onSubmitClick = (e) => {
        alert("你输入的账号是:" + this.state.account);
    };

    render() {

        return (
            <form>
                {/*这里文本框的初始值为定义值,方便绑定的事件判断*/}
                <label>用户名:</label><input type="text" width="100px" value={this.state.account} onChange={this.onInputChange}/>
                <input type="submit" value="提交" onClick={this.onSubmitClick}/>
            </form>
        );
    }
}

export  default InputTest

在App中去调用

<InputTest />
发布了35 篇原创文章 · 获赞 5 · 访问量 1470

猜你喜欢

转载自blog.csdn.net/weixin_45481406/article/details/103411184
今日推荐