React-Refs简单示例

轻鸟评职场技能 2024-07-28 21:48:43
import React from "react";const infoMap = { userNameInfo: '用户名为:', titleInfo: 'Refs - 受控组件:', inputLabelInfo: '请输入用户名 ', spaceInfo: ' ', titleTwoInfo: 'Refs - 非受控组件:', titleThreeInfo: 'Refs简单示例', subminInfo: '提交'}class ReactRefsComp extends React.Component { constructor(props) { super(props); this.state = {userName: '', output: ''}; this.handleUserNameChange = this.handleUserNameChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleUserNameChange(event) { this.setState({userName: event.target.value}); } handleSubmit(event) { event.preventDefault(); this.setState({output: infoMap.userNameInfo + this.state.userName}); } render(){ return ( <form onSubmit={this.handleSubmit}> <h3>{infoMap.titleInfo}</h3> <label>{infoMap.inputLabelInfo} <input type="text" value={this.state.userName} onChange={this.handleUserNameChange}></input> </label>{infoMap.spaceInfo} <input type="submit" value={infoMap.subminInfo}></input> <br/><br/> <p>{this.state.output}</p> </form> ); }}class ReactRefsTwoComp extends React.Component { constructor(props) { super(props); this.state = {output: ''}; this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(event) { event.preventDefault(); this.setState({output: infoMap.userNameInfo + this.userName.value}); } render(){ return ( <form onSubmit={this.handleSubmit}> <h3>{infoMap.titleTwoInfo}</h3> <label>{infoMap.inputLabelInfo} <input type="text" ref={(input) => this.userName = input}></input> </label>{infoMap.spaceInfo} <input type="submit" value={infoMap.subminInfo}></input> <br/><br/> <p>{this.state.output}</p> </form> ); }}const FormRefExample = () => { return ( <span> <h3>{infoMap.titleThreeInfo}</h3> <br/> <ReactRefsComp /> <hr/> <ReactRefsTwoComp /> </span> ) }export default FormRefExample;

0 阅读:1

轻鸟评职场技能

简介:感谢大家的关注