Reactjs React-将ref属性传递为prop
我试图通过将表单删除到不同的组件中来重构代码Reactjs React-将ref属性传递为prop,reactjs,Reactjs,我试图通过将表单删除到不同的组件中来重构代码 import React, { Component } from "react"; const collections = []; class App extends Component { constructor(props) { super(props); this.state = { data: collections, }; } handleSubmit = (e) => {
import React, { Component } from "react";
const collections = [];
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: collections,
};
}
handleSubmit = (e) => {
e.preventDefault();
const { data } = this.state,
name = this.refs.name.value;
this.setState({ data: [...data, { name }] }, () => {
this.refs.name.value = "";
});
};
render() {
return (
<div>
...
</div>
<hr />
<Form onSubmit={this.handleSubmit} myRef={(ref) => (ref = "name")} />
</div>
);
}
}
import React,{Component}来自“React”;
常量集合=[];
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
数据:收集,
};
}
handleSubmit=(e)=>{
e、 预防默认值();
const{data}=this.state,
name=this.refs.name.value;
this.setState({data:[…data,{name}]},()=>{
this.refs.name.value=“”;
});
};
render(){
返回(
...
(ref=“name”)}/>
);
}
}
表单组件将引用作为属性
const Form = ({ onSubmit, myRef }) => {
return (
<form onSubmit={onSubmit} className="mt-10 flex justify-between">
<input
className="bg-gray-300 rounded-lg px-4 py-3 outline-none"
ref={myRef}
type="text"
placeholder="Category name"
/>
<button type="submit" className="mt-5 hover:text-red-500 cursor-pointer">
Add
</button>
</form>
);
};
const Form=({onSubmit,myRef})=>{
返回(
添加
);
};
ref属性使用前面问题中的示例传递到应用程序组件中
(ref=“name”)}/>
然而,我仍然得到一个错误
您需要将ref存储在类实例变量中
<Form onSubmit={this.handleSubmit} myRef={(ref) => (this.name = ref)} />
方法2
您可以使用创建一个ref-like
constructor() {
super();
this.nameRef = React.createRef();
}
---
handleSubmit = (e) => {
e.preventDefault();
const { data } = this.state,
const name = this.nameRef.current.value;
this.setState({ data: [...data, { name }] }, () => {
this.nameRef.current.value = "";
});
};
---
<Form onSubmit={this.handleSubmit} myRef={this.nameRef} />
constructor(){
超级();
this.nameRef=React.createRef();
}
---
handleSubmit=(e)=>{
e、 预防默认值();
const{data}=this.state,
const name=this.nameRef.current.value;
this.setState({data:[…data,{name}]},()=>{
this.nameRef.current.value=“”;
});
};
---
Shubham Khatri感谢您的回答。我试过第一种方法,也试过你建议的第二种方法。然而,我仍然得到同样的错误。使用第一种方法进行演示:谢谢!!!!!!!!!!!!!!!!我传递的是const name=this.nameRef.name.value,而不是const name=this.nameRef.value,这是我的错误
handleSubmit = (e) => {
e.preventDefault();
const { data } = this.state,
const name = this.name.value;
this.setState({ data: [...data, { name }] }, () => {
this.name.value = "";
});
};
constructor() {
super();
this.nameRef = React.createRef();
}
---
handleSubmit = (e) => {
e.preventDefault();
const { data } = this.state,
const name = this.nameRef.current.value;
this.setState({ data: [...data, { name }] }, () => {
this.nameRef.current.value = "";
});
};
---
<Form onSubmit={this.handleSubmit} myRef={this.nameRef} />