React - 从 class 到 hook 的状态

React - State from class to hook

有点不明白

从我的 parents class,我像这样给我的 children class 状态:

<TrainingArea
   getHtmlGrain={() => this.getHtmlGrain()}
   right={this.state.right}
   grain_language={this.state.lang}
   id_grain={this.state.grain[this.state.currentGrain]}
   skinPath={this.state.training.skin_path}
   selectedBlock={this.state.selectedBlock}
 />

之前在 children class 中使用 'props' 我用这个 :

this.props.skinPath

但是现在,我不明白我怎么能在 'hook class react' 中使用这个道具。 或者不可能? 我的 parent class 看起来像这样:

import TrainingArea from '../Blocks/General/TrainingArea'

class BlockPage extends Component {

state = {
//some state
}

 render() {
   return (
      <TrainingArea
       getHtmlGrain={() => this.getHtmlGrain()}
       right={this.state.right}
       grain_language={this.state.lang}
       id_grain={this.state.grain[this.state.currentGrain]}
       skinPath={this.state.training.skin_path}
       selectedBlock={this.state.selectedBlock}
     />
   )}

我如何在 child class 中使用它:

const TrainingArea = (props) => {
    console.log(props.skinPath)
    return (
       <h1>hi</h1>
    )
}

useEffect(()=> {
    TrainingArea()
})

有人可以帮助我吗?非常感谢

我用这样的东西拿道具

const skin= (props) => {
    const [skin, setskin] = useState([...props.skinPath])
}

是的,这是可能的。在您的功能组件中,您可以访问提供的道具作为功能参数。例如你可以这样做:

const FunctionalComponent = (props) => {
  console.log(props.skinPath)
}

你基本上是这样走的:

class MyComponent extends React.Component {
    render() {
        const prop = this.props.prop;
        const someState = this.state.someState;
        // ...
        return <button onClick={() => this.setState({ someState: 'state' })}>Example</button>;
    };
}

对此:

function MyComponent(props) {
    const prop = props.prop;
    const [someState, setSomeState] = React.useState();
    // ...
    return <button onClick={() => setSomeState('state')}>Example</button>;
}

假设你有这样一个 parent class

class Parent extends React.COmponent {
  constructor(props) {
    super(props)
    this.state = {
      // some state data
    }
  }
  render() {
    return(
      <TrainingArea
        getHtmlGrain={() => this.getHtmlGrain()}
        right={this.state.right}
        grain_language={this.state.lang}
        id_grain={this.state.grain[this.state.currentGrain]}
        skinPath={this.state.training.skin_path}
        selectedBlock={this.state.selectedBlock}
      />
    );
  }
}

并且在 child 组件中,您需要使用此

从道具中获取一些数据
const TrainingArea = (props) => {
   console.log(props.skinPath)
   return (
     // render JSX 
   )
}