简体   繁体   中英

React Portal Functional Component

I have a problem to render an input field with an portal. When I change a the value of the input, it looses focus. I think it´s because of rerendering on state change.

https://codesandbox.io/s/zk0w1jv6rp

Does anybody know a solution?

UPDATE

Is there a way that the Bar-Componet will be reused? Lets say I could add something like a key property, so that react knows that it´s the same component and can reuse it.

Its because each time HelloReact component re-render, you are defining a new Bar component and creating a new Bar component, that is not a good approach.

Simple solution is use autoFocus , so each time when it create a new Bar component, it will focus the input element.

Working code.

Better way would be to define Bar component outside of HelloReact component and pass the value and onChange event handler in props. In that case you don't need to use autoFocus .

Example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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