单击按钮后如何显示我在文本输入字段中写的内容?

时间:2018-09-24 20:21:57

标签: javascript reactjs debugging

我想一一显示<Button/>时显示的所有已添加的内容,但是它不起作用。我尝试添加一个布尔状态showing以便触发它以显示它需要显示的内容,但是我没有运气。

我在做什么错,我该如何解决?

这里是List

import React, { Component } from 'react';
import Input from '../../containers/Input/Input';
import Button from '../../containers/Button/Button';

class List extends Component {
    constructor(props) {
        super(props);

        this.state = {
            value: '',
            showing: false

        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        this.setState({value: event.target.value});
    }

    handleSubmit(event) {
        this.setState({value: event.target.value});
    }

    displayName = () => {
        if(this.state.showing) {
            return (
                <li>{this.state.value}</li>
            );
        }
    };

    render() {
        return(
            <div>
                <form onSubmit={this.handleSubmit}>
                    <Input onchange={this.handleChange} />
                    <Button clicked={() => this.displayName()} />
                </form>
                {this.displayName()}
            </div>
        );
    }
}

export default List;

这里是Input

import React from 'react';

const input = (props) => (
    <div>
        <input type="text" onChange={props.onchange}/>
    </div>
);

export default input;

1 个答案:

答案 0 :(得分:1)

import React, { Component } from 'react';
import Input from '../../containers/Input/Input';
import Button from '../../containers/Button/Button';

class List extends Component {
    constructor(props) {
        super(props);

        this.state = {
            value: '',
            showing: false,
            latestValue: ""


        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        this.setState({
            value: event.target.value,
            showing: false,
        });
    }

    handleSubmit(event) {
        this.setState({
            showing: true,
            latestValue: this.state.value
        });
    }


    render() {
        return(
            <div>
                <input onChange={this.handleChange}/>
                <button onClick={this.handleSubmit}></button>
                <div>
                    {this.state.showing? this.state.value : this.state.latestValue}
                </div>
            </div>
        );
    }
}

export default List;

您可以尝试这个。希望对您有所帮助。