gpt4 book ai didi

javascript - 如何从子组件中的对象中获取数据并将其传递给React中父组件中的方法

转载 作者:行者123 更新时间:2023-12-02 21:07:24 25 4
gpt4 key购买 nike

我到处寻找,但没有找到方法。我只找到了如何在 React 中将数据从父级传递给子级。这就是我问这个问题的原因。我有一个父组件,它是一个表单,它从用户输入的任何内容中获取输入。但是,有一个字段它在父组件中无权访问,而在子组件的方法中访问。该字段是父组件中的“priorityLevel”,我已将其设置为 null(只是等待子组件提供该信息)。在子组件中,我使用 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 })} />

优先级选择器中:

handleSelect =(e)=> {
const priorityLevel = this.getPriorityLevel.value;
const priorityLevelData = {
priorityLevel
}
this.props.onSelect(priorityLevelData)
}

关于javascript - 如何从子组件中的对象中获取数据并将其传递给React中父组件中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61191081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com