简体   繁体   English

清除无状态React组件中的输入

[英]Clear input in stateless React component

I want to implement an X icon inside Input component that will clear the input field. 我想在Input组件内实现一个X图标,该图标将清除输入字段。 I can easily do it if I control the state. 如果我控制状态,则可以轻松完成。 But is it actually possible with stateless component? 但是无状态组件实际上有可能吗? I use react-semantic-ui, their stateful components have auto controlled state. 我使用react-semantic-ui,它们的有状态组件具有自动控制状态。

So I want to create an input that can be used like this: 所以我想创建一个可以像这样使用的输入:

 //Controlled class App extends React.Component { state = { value:'' } onChange = (event, props) => { this.setState({value: props.value}); } onClearInput = () => { this.setState({value: ''}); } render() { return ( <MyInput clearable value={this.state.value} onChange={this.onChange} onClearInput={this.onClearInput} /> ) } } 

Or 要么

 // Uncontrolled class App extends React.Component { onChange = (event, props) => { doSomething(props.value); } render() { return ( <MyInput clearable onChange={this.onChange} /> ) } } 

In the second example, clearable feature will not work because we're not controlling the value. 在第二个示例中,可clearable功能将不起作用,因为我们无法控制该值。

MyInput can be implemented like this: MyInput可以这样实现:

 import React from 'react'; import { Input } from 'semantic-ui-react'; import ClearIcon from './ClearIcon'; function MyInput(props) { const prepareProps = {...props}; if (props.clearable) { prepareProps.icon=<ClearIcon onClick={props.onClearInput} />; delete prepareProps.clearable; } delete prepareProps.onClearInput; return ( <div className="my-input"> <Input {...prepareProps} /> </div> ); } ...etc. 

My problems: 我的问题:

  1. clearable feature must work in both controlled and uncontrolled manner. clearable功能必须以受控和不受控制的方式工作。

  2. clearable feature should not require a handler. clearable功能不应要求处理程序。 It would be nice to just provide a prop and handle the render and behavior of the X button under the hood. 只需提供一个道具并处理引擎盖下X按钮的渲染和行为,那就太好了。

I don't see any way to make this work. 我看不出有什么办法可以使这项工作。 Any ideas? 有任何想法吗?

Allowing the user of your component to set the value via props and still being able to clear the input can be easily achieved, eg like this: 可以很容易地实现允许组件的用户通过props设置值并且仍然能够清除输入,例如:

class MyInput extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: props.value || ''};
    }

    handleChange = event => {
        const { onChange } = this.props;
        this.setState({ value: event.currentTarget.value });
        onChange && onChange(event);
    };

    handleClear = () => {
        const { onClearInput } = this.props;
        this.setState({ value: "" });
        onClearInput && onClearInput();
    };

    render() {
        const { value } = this.state;
        const { clearable, onChange, ...inputProps } = this.props;

        const clearIcon = clearable && <ClearIcon onClick={this.handleClear} />;

        return (
            <div className="my-input">
                <Input value={value} icon={clearIcon} onChange={this.handleChange} {...inputProps} />
            </div>
        );
    }
}

You could even make it more composable by using an hoc or render props as proposed by @pkuzhel. 您甚至可以按照@pkuzhel的建议使用hoc或渲染道具使其更具可组合性。

Look at this codesandbox example to see it in action. 查看此codeandbox示例,以查看实际效果。

@Andrey @Andrey

Would you try this below code? 您会在下面的代码中尝试吗? and let me know if that resolves your issue. 并告诉我是否可以解决您的问题。

import React, { Component } from 'react';
import { Input, Button } from 'semantic-ui-react'

class App extends Component {
  clear = () => {
    console.log(this.inputRef.target.value);
    this.inputRef.target.value = '';
  }
  render() {
    return (
      <div className="App">
        <Input placeholder='Search...' onChange={(input) => {input.persist(); this.inputRef = input}} />
        <Button onClick={this.clear}>Clear</Button>
      </div>
    );
  }
}

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

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