我有两个组成部分:
我想将标题(在子状态)的值传递给父组件。这是我的子组件的代码:
export default function ChildApp(props) {
const [titles,setTitles] = React.useState("")
return (
<Button title="submit" onPress={()=>setTitles("asma")}/>
);
}
这是我的父组件:
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} />
}
这似乎很容易做到,但这是我第一次使用功能组件。 你能帮我吗?
答案 0 :(得分:9)
反应全部是有关在组件树中向下流动的数据的。如果您希望Child
能够显示和/或修改Child
和Parent
之间的共享状态,则应lift your state up并通过props
传递给它到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)} />
}
基于类的组件
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)} />
}
}