这两者有区别吗

来源:2-7 自由编程

qq_慕九州2374973

2020-06-06 21:23:12

Ref.js:
import React, { Component, Fragment } from "react";
import TodoItem from "./TodoItem";

class Ref extends Component {

  constructor(props) {
    super(props);

    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleItemClick = this.handleItemClick.bind(this);

    this.state = {
      inputValue: 'hello React',
      list: []
    }
  }

  handleInputChange(e) {
    this.setState({
      inputValue: e.target.value
    });
  }

  handleBtnClick() {
    const list = [...this.state.list, this.state.inputValue];
    this.setState({
      list,
      inputValue: '' //清空输入框
    })
    console.log(this.inputElem.value);
    console.log(this.state.inputValue);
  }

  handleItemClick(index) {
    const list = [...this.state.list];
    list.splice(index,1);
    this.setState({ list });
  }

  handleGetItem() {
    return this.state.list.map((value, index) => {
      return(
        <TodoItem
          content={value}
          key={index}
          index={index}
          deleteFunction={this.handleItemClick}
        />
      );
    });
  }
  render() {
    return(
      <Fragment>
        <input
          type="text"
          value={this.state.inputValue}
          onChange={this.handleInputChange}
          ref={(input) => {this.inputElem = input }}
        />
        <button onClick={this.handleBtnClick}>提交</button>
        <ul>
          {this.handleGetItem()}
        </ul>
      </Fragment>
    )
  }
}

export default Ref;


TodoItem.js
import React, {Component, Fragment} from "react";

class TodoItem extends Component {

  constructor(props) {
    super(props);

    this.handleItemClick = this.handleItemClick.bind(this);
  }

  handleItemClick() {
    // this.props.deleteFunction(this.props.index);
    const {deleteFunction, index} = this.props;
    deleteFunction(index);
  }

  render() {
    const { content } = this.props;
    return (<Fragment><li onClick={this.handleItemClick}>{content}</li></Fragment>);
  }
}

export default TodoItem;


index.js
import React from 'react';
import ReactDOM from 'react-dom';

import Ref from './Ref'

ReactDOM.render( <Ref/>, document.getElementById('root'));


this.inputElem.value 和 this.state.inputValue  这两个有什么区别吗,输出的值都是一样的



写回答

1回答

好帮手慕星星

2020-06-07

同学你好,代码实现效果很棒!

针对提问问题回复:

这两个值肯定是一样,因为代码中将从输入框获取到的值,也就是this.inputElem.value赋值给 this.state.inputValue了

http://img.mukewang.com/climg/5edc53d40985a35403990134.jpg

但是我们操作的时候还是用this.state.inputValue,这样可以设置输入框初始值,以及将内容提交后设置输入框内容为空。

自己再测试理解下,祝学习愉快!

0

0 学习 · 10739 问题

查看课程