首页 > 解决方案 > Reactjs 从自定义组件中检索值

问题描述

ReactJS 的新手,我正在尝试编写自定义组件;但是,我被困在如何检索父组件中的值。

假设我有一个自定义组件输入组件:

import React,{Component} from "react";

    class TextField extends Component{
      render(){
        const inpStyle = {width:  this.props.width || "100%",height: this.props.height || ""}
        const inpClass = (this.props.error !=="" ? "error" : "")
        const autofocus= this.props.autofocus || false;
        const disabled = typeof this.props.active==="undefined"|| this.props.active===false;
        return(
          <div>
            <label htmlFor={this.props.id}>{this.props.label} </label>
            <input
              className={inpClass}
              style={inpStyle}
              id={this.props.id}
              name={this.props.id}
              value={this.props.value}
              type={this.props.type || "text"}
              disabled={!disabled}
              autoFocus={autofocus}
              placeholder={this.props.placehoder}
              onChange={this.props.handleChange}
              onFocus={this.props.handleFocus}
              onBlur={this.props.handleBlur}
            />
            <div className="errortxt">{this.props.error}</div>
          </div>
        )
      }
    }
    export default TextField

refs有没有一种方法可以在不使用或我求助的情况下检索组件值(ReactJS 方式)document.getElementById(...).value

假设 state 包含以下值,并且定义的方法确实在 Parent 组件中定义:

  render = () => {
    return(
      <div>
        <Panel width="400px" showtitle={false} shadow={true} title="Please Log In" hideclose={true}>
          <TextField
            id="emailaddress"
            label="Email Address:"
            value={this.state.fields.emailaddress.value}
            error={this.state.fields.emailaddress.error}
            autoFocus={this.state.fields.emailaddress.value !== "" ? false : true}
            handleChange={this.handleChange}
            handleFocus={this.handleFocus}
          />

标签: javascriptreactjs

解决方案


React 是关于在组件树中向下流动的数据。所以state应该归Parent. CustomInput接收 avalue以及如何从它的父级更改它。像这样的东西

const Parent = () =>{
    const[value, setValue] = useState('')

    return <CustomInput value={value} setValue={setValue} />
}

const CustomInput = ({ value, setValue }) =>(
    <input className='fancy-input' value={value} onChange={e => setValue(e.target.value) />}
)

这样,您可以在Parent不破坏正常流程的情况下“访问”输入的值,并且我将访问放在引号之间,因为您实际上并没有访问value,它property已经被Parent


推荐阅读