javascript - React js访问另一个类的状态

标签 javascript reactjs

如何访问另一个类的状态。
此构造不起作用

class classname2 extends React.Component {
  ...
  this.state = { statename1: "lala" };
  ...
};

class classname1 extends React.Component {
  render() {
    return (
       {classname2.state.statename1 } 
    );
  }
};

最佳答案

正如评论中提到的,将状态作为 Prop 传递给他们的 child 。

class classname2 extends React.Component {
  this.state = { statename1: "lala" };
  render() {
    return <classname1 statename1={this.state.statename1} />
  }
};

class classname1 extends React.Component {
  render() {
    return (
       <div>{this.props.statename1}</div>
    );
  }
};

一种常用的模式是沿着组件树传递任意 Prop :

const {needThisOne, andThisOne, ...props} = this.props;
// do stuff with needThisOne andThisOne
// and pass the remaining props down:
return <Component {...props} />;
<小时/>

钩子(Hook)的更新,因为为什么不呢。

const ParentComponent = ({...props}) => {
   const [stateName1, setStateName1] = useState('defaultValue');
   return <ChildComponent stateName1={stateName1} {...props} />;
}

const ChildComponent = ({stateName1, ...props}) => (
    <span>{stateName1}</span>
);

关于javascript - React js访问另一个类的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45664988/

相关文章:

javascript - underscorejs 如何比较两个数组?

javascript - 元素 $(this) 在 console.log 中输出不同的格式

javascript - 如何在 iPad 上使用 HTML5/Javascript 合成音频

javascript - React 组件不重新渲染,尽管 props 中的 Object 发生了变化

javascript - react 中的 "Cannot update during an existing state transition"错误

javascript - 为什么在原型(prototype)中定义属性被认为是一种反模式

javascript - 如何将 JSON 字符串转换为对象?

reactjs - 在 graphql/relay 中维护有序列表

javascript - 重新渲染 ReactJS 组件会挂起浏览器

reactjs - React Context API 和/或 React-Redux-Thunk