我到处找,但没有找到方法。我只找到了如何在 React 中将数据从父级传递给子级。所以这就是我问这个问题的原因。我有一个父组件,它是一个表单,它从用户输入的任何内容中获取输入。但是有一个字段在父组件中是没有权限访问的,在子组件的方法中可以访问。该字段是我已设置为 null 的父组件中的“priorityLevel”(只是等待子组件提供该信息)。在子组件中,我使用 ref 捕获“priorityLevel”数据并将该数据存储在“handleChange”方法中。它确实注销了选择的信息。但是,我需要将该数据传递给父组件,以便父组件可以看到并使用它。请在下面查看我的代码。
// Parent Component(TodoForm.js)
import React from "react";
import PrioritySelector from "./PrioritySelector";
import { connect } from "react-redux";
class TodoForm extends React.Component {
/*submit handler to grab input from the input references and store them
in the "todoData" object. Then dispatches an action type and payload
capturing the data. Then clears the input*/
handleSubmit=(e)=> {
e.preventDefault();
const todoTitle = this.getTodoTitle.value;
const description = this.getDescription.value;
const priorityLevel = null;
const todoData = {
id: Math.floor(Math.random()*1000),
todoTitle,
description,
priorityLevel,
editing: false
}
this.props.dispatch({type:"ADD_TODO", todoData })
this.getTodoTitle.value = "";
this.getDescription.value = "";
}
render() {
console.log(this.props)
return(
<div>
<form onSubmit={this.handleSubmit}>
<input type="text" ref={(input)=> this.getTodoTitle=input} placeholder="Enter Todo" required/>
<input type="text" ref={(input)=> this.getDescription=input} placeholder="Enter Description" required/>
<PrioritySelector />
<button>Add Todo</button>
</form>
</div>
)
}
}
export default connect()(TodoForm);
// Child Component(PrioritySelector.js)
import React from "react";
import $ from "jquery";
import { connect } from "react-redux";
class PrioritySelector extends React.Component {
componentDidMount() {
$("#selector").show();
}
handleSelect =(e)=> {
const priorityLevel = this.getPriorityLevel.value;
const priorityLevelData = {
priorityLevel
}
console.log(priorityLevelData)
}
render() {
console.log(this.props)
return(
<div>
<div className="input-field col s12">
<select onChange={this.handleSelect} ref={(option)=> this.getPriorityLevel = option} id="selector">
<option disabled selected>Choose your option</option>
<option value="1">Low</option>
<option value="2">Medium</option>
<option value="3">High</option>
</select>
</div>
</div>
)
}
}
const mapStateToProps=(state)=> {
return {
priorityLevel: state
}
}
export default connect(mapStateToProps)(PrioritySelector);
在TodoForm
:
state = {
priorityLevel: {},
}
和
<PrioritySelector onSelect={priorityLevel => this.setState({ priorityLevel })} />
在PrioritySelector
:
handleSelect =(e)=> {
const priorityLevel = this.getPriorityLevel.value;
const priorityLevelData = {
priorityLevel
}
this.props.onSelect(priorityLevelData)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句