簡體   English   中英

反應將狀態值傳遞給父級

[英]React passing state value to parent

我正在學習反應並遇到狀態值的這個問題。 我有一個功能組件(子),它有下拉框可供選擇,它們都有自己的狀態。 單擊確認按鈕時,狀態值將使用 prop 函數傳遞給父類。

(Child class)
export default function NativeSelects(props){
    const [search_title, setTitle] = useState('')
    const [search_category,setCategory] = useState('')

    return (
        <div>
            <FormControl className={classes.formControl}>
                <InputLabel htmlFor="age-native-simple">Title</InputLabel>
                <Select
                    native
                    value={search_title}
                    onChange={e => setTitle(e.target.value)}
                    inputProps={{
                        name: 'search_title',
                        id: 'age-native-simple'
                    }}
                >
                    <option value="" />
                    <option value="option1">option1</option>
                    <option value="option2">option2</option>
                    <option value="option3">option3</option>
                </Select>
            </FormControl> 
            <FormControl className={classes.formControl}>
                <InputLabel htmlFor="age-native-helper">Category</InputLabel>
                <Select
                    native 
                    value={search_category}
                    onChange={e => setCategory(e.target.value)}
                    inputProps={{
                        name: 'search_category',
                        id: 'age-native-simple'
                    }}
                >
                    <option value=""/>
                    <option value="option1">option1</option>
                    <option value="option2">option2</option>
                    <option value="option3">option3</option>
                </Select>
            </FormControl>
            <Button variant="contained" color="primary" onClick={props.handler(search_title,search_category)}>Search</Button>
        </div>
    )
}
(Parent class)
searchProduct = (title,category) =>{
    fetch(`/search?title='${title}'&category='${category}'`)
    .then(response => response.json())
    .then(response => this.setState({ products: response.data }))
    .catch(err => console.error(err))
  }

  render(){
    return (
        <ChildClass handler = {() => this.searchProduct}/>
    )
  }

當我檢查子類中的狀態值時,它正在正確更改。 但是在父類中,第一個值變成了一個對象,而第二個值變成了未定義的。 我在這里做錯了什么?

更改父類處理程序函數調用

return (
        <ChildClass handler = {(title,category)=>this.searchProduct(title,category)}/>
    )

子類的變化:

 <Button variant="contained" color="primary" onClick={(title,category)=>props.handler(search_title,search_category)}>Search</Button>

更改為在父類中跟隨。

<ChildClass handler = {this.searchProduct}/>

兒童班的變化

<Button
  variant="contained"
  color="primary"
  onClick={() => props.handler(search_title, search_category)}
>
  Search
</Button>;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM