首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的React表单没有动态更新?

为什么我的React表单没有动态更新?
EN

Stack Overflow用户
提问于 2020-10-16 17:57:07
回答 4查看 111关注 0票数 0

我是软件开发的新手。我目前正在做一个关于Codecademy的项目,在这个项目中,猫应该模仿你说的话,除非它的嘴上有胶带(附图)。几个小时后,我似乎找不到为什么我在输入字段中键入的内容在p字段中没有动态更新。任何指导都将不胜感激!

这也是我的第一篇Stack Overflow文章,所以如果我遗漏了什么,请让我知道。

cat的两种状态-没有磁带,它应该复制输入字段中的内容,反之亦然

代码语言:javascript
复制
// CopyCat.js

import React from 'react';
import { styles } from '../styles';

const images = {
  copycat: 'https://content.codecademy.com/courses/React/react_photo_copycat.png',
  quietcat: 'https://content.codecademy.com/courses/React/react_photo_quietcat.png'
};


export class CopyCat extends React.Component {
  render() {
    const copying = this.props.copying;
    const toggleTape = this.props.toggleTape;
    const input = this.props.input;
    const handleChange = this.props.handleChange;
    
    return (
      <div style={styles.divStyles}>
        <h1 style={{ marginBottom: 80 }}>Copy Cat</h1>
        <input 
          type='text'
          value={this.input}
          onChange={this.handleChange} />
        <img 
          alt='cat'
          src={copying ? images.copycat : images.quietcat}
          onClick={toggleTape}
          style={styles.imgStyles}
        />
        <p>{this.copying && this.input}</p>
      </div>
    );
  };
}

// CopyCatContainer.js

import React from 'react';
import ReactDOM from 'react-dom';
import { CopyCat } from '../components/CopyCat';

const images = {
  copycat: 'https://content.codecademy.com/courses/React/react_photo_copycat.png',
  quietcat: 'https://content.codecademy.com/courses/React/react_photo_quietcat.png'
};


class CopyCatContainer extends React.Component {
    constructor(props) {
    super(props);

    this.state = { 
      copying: true,
      input: ''
    };

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

  handleChange(e) {
    this.setState({input: e.target.value})
  }

  toggleTape() {
    this.setState({copying: !this.state.copying})
  }
  
  render() {
    const copying = this.state.copying;
    const toggleTape = this.toggleTape
    
    return (
      <CopyCat
        copying={this.state.copying}
        toggleTape={this.toggleTape} />
    );
  };
}


ReactDOM.render(<CopyCatContainer />, document.getElementById('app'));

EN

回答 4

Stack Overflow用户

发布于 2020-10-16 18:04:44

您没有将输入和handleChange方法作为属性传递给CopyCat组件

票数 1
EN

Stack Overflow用户

发布于 2020-10-16 18:04:54

您需要将输入传递给<CopyCat />组件,如下所示;

代码语言:javascript
复制
return (
  <CopyCat
    copying={this.state.copying}
    toggleTape={this.toggleTape}
    input={this.state.input}  />
);
票数 1
EN

Stack Overflow用户

发布于 2020-10-16 18:05:48

您没有将handlechange函数传递给copycat组件。通过它,它应该工作得很好。希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64386946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档