简体   繁体   English

在 react 中跟踪 children prop 的值或事件变化

[英]Track the value or event change of children prop in react

So I have a component that I use in this way.所以我有一个以这种方式使用的组件。

<SBCAInput>
  <input  defaultValue="" type="email" />
</SBCAInput>

And I implemented in the SBCAInput component like this.我在这样的SBCAInput组件中实现了。

import React , {useState} from 'react'

function SBCAInput(props) {
    const [value, setValue] = useState("");
    return (
        <div className={`sbca-input mb-3 ${ value==="" ? "" : "input-not-empty"}`}>
            <label>Email address</label>
            {props.children}
        </div>
    )
}

export default SBCAInput

Now the challenge is I want to be able to detect if the value of the input is empty and change classes on the div container in the SBCAInput component.现在的挑战是我希望能够检测input的值是否为空并更改SBCAInput组件中 div 容器上的类。

How do I track the value of the input component?如何跟踪输入组件的值?

You can access value using children.props.value :您可以使用children.props.value访问value

Parent component:父组件:

const [email, setEmail] = useState('')

function handleChange(e) {
  setEmail(e.target.value)
}

<SBCAInput>
  <input type="email" value={email} onChange={handleChange}/>
</SBCAInput>

SBCAInput component: SBCAInput 组件:

function SBCAInput({ children }) {
  return (
    <div
      className={`sbca-input mb-3 ${
        children.props.value ? 'input-not-empty' : ''
      }`}
    >
      <label>Email address</label>
      {children}
    </div>
  )
}

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

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