Elc*_*_91 2 javascript 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
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以在不使用的情况下检索组件值(ReactJS 方式),refs或者我是否求助于document.getElementById(...).value
假设 state 包含以下值,并且定义的方法确实在父组件中定义:
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}
/>
Run Code Online (Sandbox Code Playgroud)
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) />}
)
Run Code Online (Sandbox Code Playgroud)
这样您就可以“访问”输入的值,而Parent不会破坏正常流程,并且我将访问权限放在引号之间,因为您实际上并未访问value,它property已经由Parent
| 归档时间: |
|
| 查看次数: |
1809 次 |
| 最近记录: |