【问题标题】:Track the value or event change of children prop in react在 react 中跟踪 children prop 的值或事件变化
【发布时间】:2021-02-24 21:22:47
【问题描述】:

所以我有一个以这种方式使用的组件。

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

而我在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

现在的挑战是我希望能够检测input 的值是否为空并更改SBCAInput 组件中div 容器上的类。

如何跟踪输入组件的值?

【问题讨论】:

标签: javascript reactjs react-props


【解决方案1】:

您可以使用children.props.value访问value

父组件:

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

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

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

SBCAInput 组件:

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

【讨论】:

  • 如果有条件设置类变得复杂,可以使用classnames
  • 我明白了,你认为可以使用useEffect 只是为了确保,我摆脱了SBCAInput 组件中的 value 属性
  • 我试过了,它似乎不起作用,但我用了这个,它似乎对我有用`
    setValue(e.target.value) } ..... >`
猜你喜欢
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2015-01-17
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
相关资源
最近更新 更多