首页 > 解决方案 > 如何在reactjs中“通过单击提交按钮将文本区域动态移动到页面顶部”

问题描述

我想通过单击提交按钮来执行,文本区域应该移动到页面顶部并带有删除按钮右侧。每当我单击提交按钮时,文本区域应该转到页面顶部并附加上一个带有删除按钮右侧的文本区域。我附上了我的代码和codesandox链接。请帮我解决这个功能。代码沙盒演示

import React, { Component } from "react";

class App extends Component {
  constructor() {
    super();
    this.state = {
      count: [],
     
    };
}
handleSubmit(index)
  {
   
  }
 add(e) {
    this.setState({ count: [...this.state.count, ""] });
  }
 handleChange(e, index) {
    const { count } = this.state;
    count[index] = e.target.value;
    this.setState({ count });
  }
render() {
    const {  count } = this.state
    return (
      <div>
        <label>Enter the text</label>
        {count.map((counts, index) => {
          return (
            <div key={index}>
              <input
               
                onChange={(e) => this.handleChange(e, index)}
                value={counts}
              
              />
             
              <button onClick={() => this.handleSubmit(index)}>submit</button>
             
            </div>
          );
        })}
        <button  onClick={(e) => this.add(e)}> Add</button>
      </div>
    );
  }
}
export default App;
.App {
  font-family: sans-serif;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
  <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  <title>React App</title>
</head>

<body>
    <noscript>
        You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
  </body>

</html>

标签: reactjs

解决方案


有两种方法可以做到这一点,一种是css方式,另一种是javascript方式,您可以采用新的布尔状态并在单击提交按钮时更改状态,您可以使用三元运算符进行切换,否则您可以可以使用css类并在单击提交按钮时更改它,如果您需要代码告诉我,我会在这里发布


推荐阅读