This article will include the following tips:

  • How to write a Debounce Input.
  • How to publish a React component to NPM.
  • Think about how to improve yourself in your business.

react-best-input

  • It inherits the normal input attribute and can be used as an enhanced version of the normal input tag.
  • The label attribute label, which can be automatically added before input.
  • The Debounce feature, which you’ll want to use in certain scenarios, will be explained later.
  • Use the error attribute and errMsg to alert the user when the value is not expected.
  • Hint attribute is automatically configured, with the input description at the bottom.
  • GetLength, you can customize the number of characters to change the value of the returned length, used with the charBase property, default{ 'zh-cn': 1, 'eng': 1 }By default, both Chinese and English are one character long.
  • . Others, the follow-up may meet new needs will continue to add, such as full corner and half corner.

Here’s how I came to want to write this component:

Debounce Input

First of all, I really just wanted to write a Debounce input. The reasons are as follows:

  • First, the onChange for input is constantly changing, meaning that certain scenarios cannot be satisfied without debounces. For example: input to do validation, input whether email or mobile phone number, so the first input will prompt illegal, you say this is not nonsense? You’ll have to wait for me to type in a valid email address before you decide if it’s a valid email address. Here’s what happens:

<BestInput
  label='Type check'
  style={{ width: '40%'}} timer={600} /* The example above does not have a timer attribute, here set the user to listen for no other input within 600ms */ error={this.state.emailTrue} errMsg='This is not a legitimate email address'
  onChange={this.handleRegExp}
/>
Copy the code

The effect is as follows:

Of course, you can’t accomplish the above effect without input? Of course, you can use onBlur in normal input to validate the input, which means that the window is out of focus when the input is finished, or the user can validate the input when the input is finished. However, if you need to dynamically listen for input changes, you need to use onChange, and if you add validation, you need to write an additional onBlur. Now you only need one onChange to satisfy both requirements.

  • Second, in the current project, there are a number of components that use input, and changes to each input need to be fed back into another component. With Redux, each onChange in each input box triggers a large number of actions, sacrificing performance.

The company’s project will not screen shots, you understand what I mean, O(∩_∩)O ha ha ~. Just a few fewer unnecessary requests and a slight improvement in performance. I’ve always felt that even a 0.001ms improvement is significant.

  • The others should have some advantages, of course, but it doesn’t have to be debounce, it depends on the situation, otherwise why not just add debounce to the INPUT specification in HTML5. Well, ultimately it depends on your usage scenario.

[Implementation] : It’s easy to implement a Debounce input, but there are many scenarios that require debounce input. Instead of just an input, you can refer to loDash’s debounce function, read the source code, and develop it for your own scenario. I’m only going to talk about debounce input here.

setTimeout + clearTimeout

Yes, it’s as simple as that. We want to get the value of the input after the user has stopped typing for 600ms. We want to set a setTimeout of 600ms and then get the value from inside. When the setTimeout is triggered by continuous input by the user, the timer can be reset and timed again through clearTimeout, thus it is very simple to achieve our requirements.

Var textInput = document.getelementById () var textInput = document.getelementById ('test-input'); // Initialize a timer function var timeout = null; textInput.onkeyup =function(e) {// Reset timer function clearTimeout(timeout); // If there is no other input within 500ms, get the result after debounce timeout =setTimeout(function () {
        console.log('Input Value:', textInput.value);
    }, 500);
};
Copy the code

Product-driven business

The point is, as a fresh graduate of the workplace white, the company’s process is not very familiar, enter the company is nothing more than business. Review -> schedule -> development -> launch may include multiple changes to the product. Ha ha, I am not specific to the product. Therefore, for me, WHAT I do is the business I should do, but it may not be the business I want to do. However, every time I make a requirement, I think we still need to think about why we do it and why we change it to this way. The product must have its own ideas, and it may be more in line with the logic of users and so on. Please donate said, began to get into the business, is obviously a lot of to have what relation, this article has something to do, of course, I can’t see little title? Product drives business! There is a requirement in the project: get user input, and then no more than 10 characters, but the Chinese characters count 1, English letters and numbers count 0.5. It’s not a complicated requirement. Just take the input and match it and recalculate the length return. The question is, what if multiple components use this requirement but have different requirements? For example, page A requires 1 Chinese and 1 English, and page B requires 2 Chinese and 1 English. Wouldn’t each of these have to be written with a corresponding function. So, incidentally, I’ve added this requirement to react-best-input as well. You can configure the charBase property to change the character, and then use getLength to get a custom input length.

charBase {
    'zh-cn': number// Chinese character length,'eng': number// English character length} getLength(length) // Obtains the user-defined lengthCopy the code

How to publish a React component to NPM

Finished development, the release component to NPM, the steps are particularly simple, the first is to configure the various configurations of webpack, everyone configuration is not the same, you can refer to a variety of documents to configure a suitable for you, I will not introduce, because I also in learning, O(∩_∩) ha ha ~.

By default, WebPack4 + is compressed code, which comes with uglifyJs, so you can use webPack — Mode Devlopment to see the packed code while you’re developing, as well as my configuration.

  • Yarn Build package your code. For simplicity, the package will present the corresponding file in the specified folder. Mine is the index.js file in lib.
  • Release step 2: Yarn Link development is finished, of course, need to test, otherwise you release the package installed by others found that can not use it is not very embarrassing!! With YARN Link, this command will help you create a local reference package command so that you can use the command locally to test whether your package is correct

Yarn link “react-best-input” is valid only if the local test uses double quotation marks to reference the package name.

  • Yarn publish test is complete. If the yarn publish test is complete, it is ready to publishyarn publishCommand to publish, of course, you need to register your account in NPM, registration process is not to say. Your login information is required for the first release, after which your package will be published.

    There is also a small hole here: it seems that the mailbox of NPM registration cannot be used as a domestic mailbox, otherwise there will be an error, I have not tested, but I have registered with 126 mailbox for five times without success, but I have registered with Gmail mailbox once, the same account name and password…

  • Update also uses YARN Publish, but it will prompt you for the current version and the version you want to publish. If the current version is V1.0.1, you only need to change a different version number to update it.

Record on pit

The react grammar pit

If the react syntax is used instead of a native JS package, you will need to use Babel to translate es5 code into webpack. Babel-preset -react,babel-preset- ES2015 and babel-preset-stage-1 are needed.

SSR pit

Server rendering, is a word to the fire, may also have most of the programs are in use, I’m trying to say is not the problem, I want to say is that if you write the components with the help of the underlying such as Windows, document these variables, then in the rendering of a service is a hard, just in general is a node, the node is not the above two variables. Because I’m using input and using styles, style-loader will use the underlying Document. querySelector to find the DOM node insertion style, so the package will render on the server with an error: Window is not defined.

[Solution] : soldiers will block, water to soil tun. The solution is to use webpack import() to load components asynchronously, which is not necessarily rendered on the server. So I wrote an extra component that loads asynchronously and can be used if needed: rC-async-Component. It should be called act-async-component, but it was registered a month ago.

. import asyncComponent from'rc-async-component'; . const BestInput = asyncComponent(() => import('react-best-input')); .render() {
    return (
        <BestInput />
    )
}

Copy the code

To emphasize, non-server rendering can be used directly without any problems, server rendering currently needs to be loaded asynchronously, there may be a better solution in the future when the documentation will be updated.

conclusion

If see this still can stick to see, I really thank you, feel their level is limited, will continue to improve! I think it is meaningful to help a person

Portal:react-best-input,rc-async-component

If you like it, thank star, I will be very happy