在 React 中,我有类似的文件
--parent.js
--child.js
--App.js
parent.js 包含文本框和按钮
child.js包含P标签
App.js 包含父组件和子组件
问题
单击按钮时将文本框值从父级传递给子级,并在子段落标记中显示该值。
完整代码 stackblitz
最佳答案
更新了您的示例以将数据传递给子组件。
https://stackblitz.com/edit/react-trmj9i?file=child.js
添加下面的代码以供快速引用
index.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import Parent from './parent';
import Child from './child';
import './style.css';
class App extends Component {
constructor() {
super();
this.state = {
name: 'React',
parentTextBoxValue: ''
};
}
handleParentData = (e) => {
this.setState({parentTextBoxValue: e})
}
render() {
return (
<div>
<Parent handleData={this.handleParentData} />
<Child parentTextBoxValue={this.state.parentTextBoxValue}/>
</div>
);
}
}
render(<App />, document.getElementById('root'));
parent.js
import React, { Component } from 'react';
import Button from 'react-uikit-button';
class Parent extends Component {
constructor(props){
super(props);
this.state={TextBoxValue: ""}
}
SubmitValue = (e) => {
this.props.handleData(this.state.TextBoxValue)
}
onChange=(e)=>{
this.setState({TextBoxValue: e.target.value})
}
render() {
return (
<div className="">
<input type="text" name="TextBox" onChange={this.onChange}
/>
<Button onClick={this.SubmitValue}>Submit Value</Button>
</div>
);
}
}
export default Parent;
child.js
import React, { Component } from 'react';
class Child extends Component {
constructor(props){
super(props);
}
render() {
return (
<div className="App">
<p>{this.props.parentTextBoxValue}</p>
</div>
);
}
}
export default Child;
只是为了奉献我所做的, 将一个函数从 App.js 传递给父级,这可以帮助提升状态。 处理文本框父组件中的 onchange 以及提交更新的应用程序状态。 最后将此状态传递给子组件。
关于reactjs - react |将数据从父组件传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48952882/