将值从子组件传递给父组件 [英] Pass values from children to parent component
问题描述
我有两个组件:
- 第一个是父组件,它是一个常见的 React 组件.
- 第二个是子组件,它是一个功能组件.
我想将Titles(在子状态)的值传递给父组件.这是我的子组件代码:
导出默认函数 ChildApp(props) {const [titles,setTitles] = React.useState("")返回 (<Button title="submit" onPress={()=>setTitles("asma")}/>);}
这是我的父组件:
<预><代码>this.state = { 标题:"foo"}setTitles = 标题 =>this.setState({titles})//我需要在 state 中设置 Titles 的值导出默认类ParentApp扩展组件{const titles = this.state.titles<ChildApp titles={titles} setTitles={this.setTitles}/>}这看起来很容易,但对我来说这是第一次使用功能组件.你能帮我吗?
React 是关于在组件树中向下流动的数据.如果您希望 Child
能够显示和/或修改 Child
和 Parent
之间的共享状态,您应该 提升你的状态并通过props
传递给它的children
const Parent = () =>{const [title, settitle] = useState('foo')return <Child title={title} setTitle={setTitle}/>}const Child = ({ title, setTitle}) =>{return setTitle(e.target.value)}/>}
基于类的组件
class Parent 扩展 React.Component{状态 = { 标题:'' }setTitle = 标题 =>this.setState({标题})使成为(){const { 标题} = this.statereturn <Child title={title} setTitle={this.setTitle}/>}}class Child 扩展 React.Component{使成为(){const { title, setTitle } = this.propsreturn setTitle(e.target.value)}/>}}
I have two components :
- The first one is the parent Component which is a usual React Component.
- The second one is the child which is a functional component.
I want to pass the value of Titles (in the child state) to the parent Component. Here is my code of Child Component:
export default function ChildApp(props) {
const [titles,setTitles] = React.useState("")
return (
<Button title="submit" onPress={()=>setTitles("asma")}/>
);
}
And here is my Parent Component :
this.state = { titles:"foo"}
setTitles = titles => this.setState({ titles })
// i need the value of Titles to be set in state
export default class ParentApp extends Component {
const titles = this.state.titles
<ChildApp titles={titles} setTitles={this.setTitles} />
}
It seems easy to do but it's the first time for me working with functional components. Can you help me please ?
React is all about data flowing down in the components tree. If you want your Child
to be able to show and/or modify a shared state between Child
and Parent
you should lift your state up and pass it down via props
to it's children
const Parent = () =>{
const [title, settitle] = useState('foo')
return <Child title={title} setTitle={setTitle} />
}
const Child = ({ title, setTitle}) =>{
return <input value={title} onChange={e => setTitle(e.target.value)} />
}
In class based components
class Parent extends React.Component{
state = { title: '' }
setTitle = title => this.setState({ title })
render(){
const { title } = this.state
return <Child title={title} setTitle={this.setTitle} />
}
}
class Child extends React.Component{
render(){
const { title, setTitle } = this.props
return <input value={value} setTitle={e => setTitle(e.target.value)} />
}
}
这篇关于将值从子组件传递给父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!