React初级_添加爱好显示列表

效果如图:
在这里插入图片描述
代码:

import React from 'react';

class Hobby extends React.Component {
    
    
    constructor(props) {
    
    
        super(props);
        this.state = {
    
    
            ...this.state,
            hobbies: this.props.hobbies || []
        }
        this.addHobbyCallback = this.addHobbyCallback.bind(this);
    }

    addHobbyCallback() {
    
    
        // 用this.refs.name来取得DOM节点
        let hobbyInput = this.refs.hobby;
        let nameInput = this.refs.name;
        let val = hobbyInput.value + " " + nameInput.value;
        if (hobbyInput.value && nameInput.value) {
    
    
            let hobbies = this.state.hobbies;
            hobbies = [...hobbies, val];
            this.setState({
    
    
                hobbies
            }, () => {
    
    
                hobbyInput.value = '';
                nameInput.value = '';
            });
        } else {
    
    
            console.log("空语句.");
        }
    }

    render() {
    
    
        const btnStyle = {
    
    
            margin: "6px"
        }
        let i = 1;
        return (
            <div>
                <span>姓名: </span>
                <input type="text" ref="hobby" style={
    
    btnStyle} />
                <span>爱好:</span>
                <input type="text" ref="name" style={
    
    btnStyle} />
                <button style={
    
    btnStyle} onClick={
    
    this.addHobbyCallback}>添加爱好</button>
                {
    
    
                    this.state.hobbies.map(item => {
    
    
                        return (<li key={
    
    i}>{
    
    `${
      
      i++}, ${
      
      item}`}</li>)
                    }
                    )
                }
            </div>
        )
    }
}

export default Hobby;

猜你喜欢

转载自blog.csdn.net/kuilaurence/article/details/109032565