繁体   English   中英

如何在 Reactjs 中重置组件

[英]How to reset components in Reactjs

我有 2 个组件作为表单(Dropzone.js 和 TextEditor.js),在我的主页的一部分中被调用。 我正在使用上下文来获取每个输入并发送到我的后端,是否可以在发送数据后删除每个组件的输入?

Dropzone.js

function FileUploader(){
  const { input ,setInput } = useContext(InputContext);
  
    // specify upload params and url for your files
  const getUploadParams = ({ meta }) => { return { url: 'https://httpbin.org/post' } }
  
  // called every time a file's `status` changes
  const handleChangeStatus = ({ file, remove }, status) => {
     if (status === 'done'){
       console.log(file)
       setInput({
         file: file,
         text: input.text
        })
      }
      console.log(status)
  }

  const Preview = ({ meta, fileWithMeta}) => {
    const { name, percent} = meta
    const { remove } = fileWithMeta
    return (
      <Container>
          <span style={{ alignSelf: 'flex-start',fontFamily: 'Helvetica', marginLeft: '0%', fontSize: '14px'}}>
            {name}
          </span>
          <ProgressBar value={percent} max="100"></ProgressBar>
          <span onClick={remove}><CancelIcon></CancelIcon></span>
      </Container>
    )
  }

    return(
        <Dropzone
        getUploadParams={getUploadParams}
        onChangeStatus={handleChangeStatus}
        PreviewComponent={Preview}
        accept="application/pdf, text/plain"
        inputContent="Insira aqui seu arquivo de comparação"
        multiple={false}
        maxFiles={1}
        styles={{ dropzone: {backgroundColor: '#fffef7', margin: 'auto', width: "300px", overflow: "auto", maxWidth: "100%"}, inputLabel: {fontFamily: "'Lato', sans-serif", color: "#808080", fontSize: "1.2em", fontWeight: 400} }}
        />
      );
};

export default FileUploader;

文本编辑器.js

import React, {useState, useContext} from 'react';
import {Editor, EditorState, RichUtils} from 'draft-js';
import InputContext from '../../InputContext';
import { SaveIcon, SaveButton, Container} from './styles';
import 'draft-js/dist/Draft.css';

function TextEditor(){

    const { setInput, input } = useContext(InputContext);

    //Configuração de estado do editor
    const [ editorState, setEditorState ] = useState(
        () => EditorState.createEmpty(),
    );

    //Configuração do handleKeyCommand
    const handleKeyCommand = (command, editorState) => {
        const newState = RichUtils.handleKeyCommand(editorState, command);

        if (newState) {
            setEditorState(newState);
            return 'handled';
        }
        return 'not-handled';
    };

    const onSave =  () => {
        const current = editorState.getCurrentContent();
        const text = current.getPlainText('\u0001')
        if( current.hasText()){
            console.log(text)
            setInput({
                text: text,
                file: input.file
            })
        }
    }

    return(
        <Container>
            <Editor
             editorState={editorState}
             handleKeyCommand={handleKeyCommand} 
             onChange={setEditorState}
             placeholder="Insira seu texto aqui"
             ariaLabel="Input de texto para comparação"
             />
             <SaveButton aria-label="Salvar texto" onClick={onSave}><SaveIcon aria-hidden="true" focusable="false"/></SaveButton>
        </Container>
    );
}

export default TextEditor;

Apresentacao.js(首页部分)

const Apresentacao = () => {

    const { input ,setInput } = useContext(InputContext);

    const submitData = () => {
      if (input.text !== null && input.file !== null){
        console.log(input)
      }
      else if (input.text === null && input.file !== null ){
        console.log("Insira seu texto e não se esqueça de salvá-lo!")
      }
      else if (input.text !== null && input.file === null){
        console.log("É necessário enviar um arquivo para realizarmos a comparação com seu texto!")
      }

      setInput({
        file: null,
        text: null
      });
    }

    return <div>
            <Imagem>
              <PageTitle>Detector de plágio e comparador de textos</PageTitle>
              <Text>Online <br/> Aqui, agora, sempre e em todo lugar</Text>
              <Container>
                <TextEditor/>
                <ColumnContainer>
                  <FileUploader/>
                  <SmallText> Não esqueça de salvar seu texto antes de checá-lo!</SmallText>
                  <Button onClick={submitData}> Checar plágio</Button>
                </ColumnContainer>   
              </Container>
            </Imagem>
    </div>
}

export default Apresentacao;

对的,这是可能的。 由于您在提交表单后将上下文的值设置为null并且您的TextEditorDropzone组件可以访问此上下文,因此您可以在这两个组件内侦听上下文值的更改并在input.textinput.file时重置它们的input.file等于null 您可以使用useEffect实现这useEffect

文本编辑器.js

function TextEditor(){

    const { setInput, input } = useContext(InputContext);

    const [ editorState, setEditorState ] = useState(
        () => EditorState.createEmpty(),
    );

    React.useEffect(() => {
        if(input === null) {
            setEditorState(() => EditorState.createEmpty());
        }
    }, [input]);

    [...]
}

我不知道你使用的Dropzone组件是如何工作的,所以我不能告诉你如何重置它的状态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM