我正在尝试将数据从子组件发送到其父组件,如下所示:
const ParentComponent = React.createClass({
getInitialState() {
return {
language: '',
};
},
handleLanguageCode: function(langValue) {
this.setState({language: langValue});
},
render() {
return (
<div className="col-sm-9" >
<SelectLanguage onSelectLanguage={this.handleLanguage}/>
</div>
);
});
这是子组件:
export const SelectLanguage = React.createClass({
getInitialState: function(){
return{
selectedCode: '',
selectedLanguage: '',
};
},
handleLangChange: function (e) {
var lang = this.state.selectedLanguage;
var code = this.state.selectedCode;
this.props.onSelectLanguage({selectedLanguage: lang});
this.props.onSelectLanguage({selectedCode: code});
},
render() {
var json = require("json!../languages.json");
var jsonArray = json.languages;
return (
<div >
<DropdownList ref='dropdown'
data={jsonArray}
value={this.state.selectedLanguage}
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
});
我需要的是在父组件中获取用户选择的值。我收到此错误:
Uncaught TypeError: this.props.onSelectLanguage is not a function
谁能帮我找到问题?
PS 子组件正在从 json 文件创建下拉列表,我需要下拉列表来显示 json 数组的两个元素彼此相邻(例如:“aaa,english”作为首选!)
{
"languages":[
[
"aaa",
"english"
],
[
"aab",
"swedish"
],
}
<SelectLanguage onSelectLanguage={this.handleLanguage*Code*}/>
一个错字。
handleLanguageCode: function(langValue) { this.setState({ language: langValue }).bind(this); },
但它返回错误:ncaught TypeError: Cannot read property 'bind' of undefined
createClass
自动绑定非反应方法。
这应该有效。在发回道具时,您将其作为对象发送,而不是将其作为值发送,或者将其用作父组件中的对象。其次,您需要格式化您的 json 对象以包含名称值对并使用 DropdownList
的 valueField
和 textField
属性
简答
家长:
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
孩子:
handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}
详细的:
编辑:
考虑到 React.createClass 从 v16.0 起已弃用,最好继续通过扩展 React.Component
创建一个 React 组件。使用这种语法将数据从子组件传递到父组件看起来像
家长
class ParentComponent extends React.Component {
state = { language: '' }
handleLanguage = (langValue) => {
this.setState({language: langValue});
}
render() {
return (
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
)
}
}
孩子
var json = require("json!../languages.json");
var jsonArray = json.languages;
export class SelectLanguage extends React.Component {
state = {
selectedCode: '',
selectedLanguage: jsonArray[0],
}
handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}
render() {
return (
<div>
<DropdownList ref={(ref) => this.dropdown = ref}
data={jsonArray}
valueField='lang' textField='lang'
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
}
使用 OP 在他的回答 Parent 中使用的 createClass
语法
const ParentComponent = React.createClass({
getInitialState() {
return {
language: '',
};
},
handleLanguage: function(langValue) {
this.setState({language: langValue});
},
render() {
return (
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
);
});
孩子
var json = require("json!../languages.json");
var jsonArray = json.languages;
export const SelectLanguage = React.createClass({
getInitialState: function() {
return {
selectedCode: '',
selectedLanguage: jsonArray[0],
};
},
handleLangChange: function () {
var lang = this.refs.dropdown.value;
this.props.onSelectLanguage(lang);
},
render() {
return (
<div>
<DropdownList ref='dropdown'
data={jsonArray}
valueField='lang' textField='lang'
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
});
JSON:
{
"languages":[
{
"code": "aaa",
"lang": "english"
},
{
"code": "aab",
"lang": "Swedish"
},
]
}
将数据从子组件传递到父组件
在父组件中:
getData(val){
// do not forget to bind getData in constructor
console.log(val);
}
render(){
return(<Child sendData={this.getData}/>);
}
在子组件中:
demoMethod(){
this.props.sendData(value);
}
this.getData = this.getData.bind(this);
,因为如果你想在 getData 中操作状态,你可能会得到 this.setState 不是一个函数。
考虑到 React 函数组件和使用 Hooks 越来越流行,我将举一个简单的例子来说明如何将数据从子组件传递到父组件
在父功能组件中,我们将拥有:
import React, { useState } from "react";
然后
const [childData, setChildData] = useState("");
并将 setChildData(在类组件中执行类似于 this.setState 的工作)传递给 Child
return( <ChildComponent passChildData={setChildData} /> )
在子组件中,我们首先获得接收道具
function ChildComponent(props){ return (...) }
然后你可以像使用处理函数一样传递数据
const functionHandler = (data) => {
props.passChildData(data);
}
在 React v16.8+
函数组件中,您可以使用 useState()
创建一个函数状态,让您更新父状态,然后将其作为 props 属性传递给子组件,然后在子组件内部您可以触发父状态函数,以下是一个工作片段:
常量 { useState , useEffect } = 反应;函数 Timer({ setParentCounter }) { const [counter, setCounter] = React.useState(0); useEffect(() => { let countersystem; countersystem = setTimeout(() => setCounter(counter + 1), 1000); return () => { clearTimeout(countersystem); }; }, [counter]); return (
您可以使用 useState
在 ParentComponent 中创建状态,并将 setIsParentData
函数作为 prop 传递给 ChildComponent。
在 ChildComponent 中,使用接收到的函数通过 prop 更新数据,将数据发送回 ParentComponent。
我使用这种技术,尤其是当我在 ParentComponent 中的代码变得太长时,因此我将从 ParentComponent 创建子组件。通常,它只会下降 1 级,并且使用 useContext 或 redux 似乎有点过分了,以便在组件之间共享状态。
ParentComponent.js
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
export function ParentComponent(){
const [isParentData, setIsParentData] = useState(True);
return (
<p>is this a parent data?: {isParentData}</p>
<ChildComponent toChild={isParentData} sendToParent={setIsParentData} />
);
}
ChildComponent.js
import React from 'react';
export function ChildComponent(props){
return (
<button onClick={() => {props.sendToParent(False)}}>Update</button>
<p>The state of isParentData is {props.toChild}</p>
);
};
我找到了如何在需要时从父母的子组件中获取数据的方法。
家长:
class ParentComponent extends Component{
onSubmit(data) {
let mapPoint = this.getMapPoint();
}
render(){
return (
<form onSubmit={this.onSubmit.bind(this)}>
<ChildComponent getCurrentPoint={getMapPoint => {this.getMapPoint = getMapPoint}} />
<input type="submit" value="Submit" />
</form>
)
}
}
孩子:
class ChildComponent extends Component{
constructor(props){
super(props);
if (props.getCurrentPoint){
props.getCurrentPoint(this.getMapPoint.bind(this));
}
}
getMapPoint(){
return this.Point;
}
}
这个例子展示了如何将函数从子组件传递给父组件,并使用此函数从子组件获取数据。
从子组件到父组件如下
父组件
class Parent extends React.Component {
state = { message: "parent message" }
callbackFunction = (childData) => {
this.setState({message: childData})
},
render() {
return (
<div>
<Child parentCallback = {this.callbackFunction}/>
<p> {this.state.message} </p>
</div>
);
}
}
子组件
class Child extends React.Component{
sendBackData = () => {
this.props.parentCallback("child message");
},
render() {
<button onClick={sendBackData}>click me to send back</button>
}
};
我希望这项工作
在这里,我试图以最简单的方式进行解释:我正在从子组件更新父组件计数器。
父组件 (PropsApp.jsx)
import React, { useState } from 'react'
import Child from './Child'
export default function PropsApp(){
const [counter, setCounter] = useState(0)
const updateMyCounter = () => {
setCounter(counter + 1)
}
return(
<>
<hr></hr>
<h1>This is Parent</h1>
<h2>{counter}</h2>
<Child updateParent={updateMyCounter} />
</>
)
}
子组件 (Child.jsx)
export default function Child(props){
return(
<>
<hr></hr>
<h1>This is Child</h1>
<button
onClick={props.updateParent}
>
Update Parent Component
</button>
</>
)
}
https://i.stack.imgur.com/b7FZE.png
最近找到了一种很好且简单的方法来通过输入来做到这一点。
本质上,我只是 useState,然后将 onChange 设置为子组件的道具,它将“值”作为参数并将其放入 useState“setVal”boom 我每次都得到状态更改子 -> 父
const Parent = () => {
const [val, setVal] = useState("initial value")
return(
<>
<Child onChange={(value)=> setVal(value)}/>
<div>{val}</div>
</>
)
};
export default Parent;
const Child = (props) => {
return(
<button onClick={() => props.onChange("your value here") }>
)
}
React.createClass 方法在新版本的 React 中已被弃用,您可以非常简单地通过以下方式使一个功能组件和另一个类组件保持状态:
家长:
const ParentComp = () => { getLanguage = (language) => { console.log('Language in Parent Component: ', language); }
孩子:
类 ChildComp 扩展 React.Component { state = { selectedLanguage: '' } handleLangChange = e => { const language = e.target.value; thi.setState({ selectedLanguage = 语言; }); this.props.onGetLanguage({language}); } render() { const json = require("json!../languages.json");常量 jsonArray = json.languages; const selectedLanguage = this.state; return (
这个想法是向孩子发送一个回调,该回调将被调用以返回数据
使用函数的完整且最小的示例:
应用程序将创建一个子节点,该子节点将计算一个随机数并将其直接发送回父节点,父节点将 console.log
结果
const Child = ({ handleRandom }) => {
handleRandom(Math.random())
return <span>child</span>
}
const App = () => <Child handleRandom={(num) => console.log(num)}/>
使用回调将数据从子组件传递到父组件
You need to pass from parent to child callback function, and then call it in the child.
父组件:-TimeModal
handleTimeValue = (timeValue) => {
this.setState({pouringDiff: timeValue});
}
<TimeSelection
prePourPreHours={prePourPreHours}
setPourTime={this.setPourTime}
isPrePour={isPrePour}
isResident={isResident}
isMilitaryFormatTime={isMilitaryFormatTime}
communityDateTime={moment(communityDT).format("MM/DD/YYYY hh:mm A")}
onSelectPouringTimeDiff={this.handleTimeValue}
/>
注意:- onSelectPouringTimeDiff={this.handleTimeValue}
在需要时在子组件中调用道具
componentDidMount():void{
// Todo use this as per your scenrio
this.props.onSelectPouringTimeDiff(pouringDiff);
}
您甚至可以避免父级的函数直接更新状态
在父组件中:
render(){
return(<Child sendData={ v => this.setState({item: v}) } />);
}
在子组件中:
demoMethod(){
this.props.sendData(value);
}
将数据从子组件传递到父组件的最佳方法
子组件
handleLanguageCode=()=>(langValue) {
this.props.sendDatatoParent(langValue)
}
家长
<父母 sendDatatoParent={ 数据 => this.setState({item: data}) } />;
import { useEffect, useState } from "react";
export default function App() {
const data = (data) => {
console.log("data", data);
};
const myData = {
name: "hi this is my data"
};
return <Form onSubmit={data} myDatasa={myData} />;
}
const Form = (props) => {
console.log("myData", props.myDatasa.name);
const [choreDesc, setChoreDesc] = useState();
const handleSubmit = (e) => {
e.preventDefault();
props.onSubmit(choreDesc);
};
const handlechange = (e) => {
setChoreDesc(e.target.value);
};
return (
<form
onSubmit={(e) => {
handleSubmit(e);
}}
>
<label>Chore description:</label>
<br />
<input
name="choreDesc"
type="text"
value={choreDesc}
onChange={handlechange}
/>
<br />
<input type="submit" value="Add Log" />
</form>
);
};
```
不定期副业成功案例分享