清除动态添加的输入字段

时间:2019-09-04 09:39:40

标签: reactjs algorithm input

我正在创建一个应用程序,用户应在其中重新组合一个正确的句子。如下图所示。问题是我没有以正确的方式实施该应用程序。例如,我不会通过状态更改输入。我的主要问题是如何清除特定行的输入(一堆输入)?用户输入错误并需要重新启动时,我需要它。我知道应该通过状态来控制输入字段,但是由于所有输入都是根据字数生成的,因此这是不可能的。一行中可能有多个输入。让我解释一下我的代码是如何工作的,以便您对我的实现有所了解。

这是我从那里获取数据的地方。

export default {
    id:'1',
    parts:[
    {
        speaker:'Speaker1',
        words:'Hello how are you?'
    },
    {   speaker:'Speaker2',
        words:'I am OK, thanks'
    },
    {   speaker:'Speaker1',
        words:'What are your plans for Saturday?'
    }
    ]
}

import React, { Component } from 'react';
import {CopyToClipboard} from 'react-copy-to-clipboard';
import { MdDoneAll } from "react-icons/md";


// This is the array where data from inputs is pushed to
var pushArr = [];

// Initial points 
var points = 0;

class DialogueShuffleFrame extends Component {
    constructor(props) {
        super(props)

        this.state = {
            // Variable to show correct or incorrect notification
            showCorrect:false
        }

        this.writeSometihng = this.writeSometihng.bind(this)
    }

    // Function that is triggered when a tick is clicked
    // Pushes value to the pushArr array when onBlur function is triggered

    writeSometihng(e) {
        e.preventDefault()
        pushArr.push(e.target.value)
        console.log(pushArr)
    }

    // Function check if array of value from input matches to an array from
    // initial data source
    checkLines(arr, lines) {
        let joinedStr = arr.join(' ');
        //console.log(joinedStr);
        lines[0].parts.map((obj) => {
            let line = obj.words
            if (joinedStr === line) {
                this.setState({
                    showCorrect:true
                })
                pushArr = [];
                points += 80;
            } else {
                pushArr = [];
            }

        })
    }

    // Resets pushArr array
    reset() {
        pushArr.length = 0
        console.log('clicked')
    }
    // Shuffles words 
    formatWords(words) {
        const splittedWords = words.split(' ')
        const shuffledArray = this.shuffle(splittedWords)
        return (
            shuffledArray.map((word, index) => (
                <>
                    <input className="word-to-drop-input" id={index} onBlur={this.writeSometihng} size={2} />
                    <CopyToClipboard text={word}>
                        <span key={uid(word)} value={word} className="word-to-drop">{word}</span>
                    </CopyToClipboard>
                </>
            ))
        )
    }

    shuffle(a) {
        var j, x, i;
        for (i = a.length - 1; i > 0; i--) {
            j = Math.floor(Math.random() * (i + 1));
            x = a[i];
            a[i] = a[j];
            a[j] = x;
        }
        return a;
    }

    render() {
        const {lines} = this.props
        const shuffles = lines[0].parts && (
            lines[0].parts.map((element,i) => (
                <>
                    <li className="line" key={i}><span>{element.speaker}{": "}</span><span>{this.formatWords(element.words)}</span></li>
                    <MdDoneAll type="button" onClick={() => {this.checkLines(pushArr, lines)}} style={{color:'white'}}/>
                </>
            ))
        )

        return (
                <>
                    <h1 className="centered" style={{color:'white'}}>Dialogue shuffle frame</h1>
                    <ul className="lines-container">
                        {shuffles}
                    </ul>
                    {<div className="reactangular">{this.state.showCorrect ? 'Correct' : 'Incorrect'}</div>} 
                    <div>{points}</div> 
                    <div className="reactangular" onClick={() => this.reset()}>Reset</div>
                </>
        )
    }
}

export default DialogueShuffleFrame;

enter image description here

1 个答案:

答案 0 :(得分:1)

我建议在状态管理中使用适当的数据结构,但这是另一回事。

要解决清除输入元素的特定问题,可以使用ReactDOM.findDOMNode访问DOM节点并遍历input元素并将值设置为空字符串。

类似这样的东西:

class App extends React.Component {
  
  check = (ref) => {

    const inputElements = ReactDOM.findDOMNode(ref.target).parentNode.getElementsByTagName('input');
    
    [...inputElements].forEach(el => el.value = '')
    
  }
  
  render() {
    return (
      <div>
        <ul>
          <li>
            <input />
            <input />
            <button onClick={this.check}>Check</button>
          </li>
          <li>
            <input />
            <input />
            <input />
            <button onClick={this.check}>Check</button>
          </li>
        </ul>
      </div>
    );
  }
  
}

ReactDOM.render(<App />, document.getElementById('app'));
<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>

<div id="app"></div>