认为我有一个组件:
<Component1>
<Component2 value={0}/>
{window.console.log(Component2.value)}
</Component1>
该如何执行window.console.log的工作,因为尝试连接该道具时遇到问题。
答案 0 :(得分:0)
为什么不从component1
的状态访问该值?
class Component1 extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
this.incrementCounter = this.incrementCounter.bind(this);
}
incrementCounter() {
this.setState(prevState => ({ counter: prevState.counter + 1 }));
}
render() {
return (
<View>
<Component2
incrementCounter={this.incrementCounter}
counter={this.state.counter} />
<Component3 counter={this.state.counter} />
</View>
)
}
}
最后位于Component2内部
<button onClick={this.props.incrementCounter}>
click to increment counter
</button>
这是React的第一法则,子组件不会改变数据 他们通过传递给他们的方法与父组件交谈。这也使数据流更好,实际上这就是您应该使用React的方式。
答案 1 :(得分:0)
基本上,您需要做的是将回调函数作为<Component2>
传递给prop
,该回调函数返回更新为<Component1>
的值(我做了一点StackBlitz => https://stackblitz.com/edit/react-rym9h9?file=Component2.js),这里有示例:
<Component1>:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Component2 from './Component2';
import './style.css';
class Component1 extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
getUpdatedValue = (updatedValue) => {
console.log('Here is your updated value: ', updatedValue);
};
render() {
return (
<div>
<Component2 value={0} returnUpdatedValue={this.getUpdatedValue} />
<p>
Start editing to see some magic happen :)
</p>
</div>
);
}
}
render(<Component1 />, document.getElementById('root'));
<Component2>:
import React, { Component } from 'react';
class Component2 extends Component {
componentDidMount() {
const { value, returnUpdatedValue } = this.props;
let updateValue = value + 100;
returnUpdatedValue(updateValue)
};
render() {
const { value } = this.props;
return (
<div>
<h1>{value}</h1>
</div>
);
}
}
export default Component2;