将 React 值从子级传递给父级

Ste*_*e M 3 rxjs reactjs material-ui

我正在努力解决一些可能非常简单的问题。我的父组件是一个 Search 小部件,它需要使用单独的 Drawer 组件中定义的过滤器。目前用户可以输入一个搜索查询,它调用一个API,它需要根据抽屉组件的选择器过滤结果。但是,我无法链接父母和孩子来实现这一点!!

父组件(包括其中的 '' 组件):

function SuburbSearch(props: Props) {
    const classes = useStyles();
    const [value, setValue] = React.useState<App.Suburb | null>(null);
    const [inputValue, setInputValue] = React.useState('');
    ...
    
    return (
    <Autocomplete
      id="search"
      getOptionLabel={(option) => (typeof option === 'string' ? option : option.name + ' ' + option.state)}
      filterOptions={(x) => x}
      options={options}
      ...
      ...
      renderInput={(params) => (
        <TextField
          {...params}
          label="Search for a suburb"
          ...,
            startAdornment: (
              <InputAdornment position="start">
                <Filters></Filters>
              </InputAdornment>
            ),
            endAdornment: (
              <React.Fragment>
                {loading ? <CircularProgress color="inherit" size={20} /> : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            ),
          }}
          fullWidth
        />
      )}
Run Code Online (Sandbox Code Playgroud)

子组件(这是“过滤器”):

export default function Filters() {
  const classes = useStyles();
  const [state, setState] = useState(false);
  const [dollar, setDollars] = useState<number[]>([0, 20000000]);
  const [type, setType] = React.useState<string | null>('all');
  
  ...
  const list = (anchor: Anchor) => (
    <div className={classes.root} 
      role="presentation" /*onClick={toggleDrawer(false)} onKeyDown={toggleDrawer(false)}/*/>
      <Grid className={classes.main} container spacing={2}>
        <Grid className={classes.row} item xs={1} md={2} />
        <Grid className={classes.row} item xs={10} md={8}>
          <Typography className={classes.header} align='center' gutterBottom>
            Property Type
          </Typography>
          <ToggleButtonGroup value={type} onChange={handleTypeChange} exclusive>
            <ToggleButton value="all" >All</ToggleButton>
            <ToggleButton value="some" >Some</ToggleButton>
          </ToggleButtonGroup>
        </Grid>
        ...
      </Grid>
   </div>
}
Run Code Online (Sandbox Code Playgroud)

k-w*_*ski 5

您可以简单地通过将函数作为道具传递来完成,如下所示:

父组件

childCallback(value) {
    // value passed from child
}

return {
    <ChildComponent passToParent={this.childCallback}/>
}
Run Code Online (Sandbox Code Playgroud)

子组件

this.props.passToParent(childValue);
Run Code Online (Sandbox Code Playgroud)