我有2个组件button和lvlchecker在react中,button.js看起来像这样:
import React from "react";
class Button extends React.Component {
state = {
clickCounter: 0
};
handleClick = () => {
this.setState(prevState => {
return { clickCounter: prevState.clickCounter + 1 };
});
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click</button>
<p>CLICKS: {this.state.clickCounter}</p>
</div>
);
}
}
export default Button;
我想将数据从此组件(clickCounter函数)传输到其他组件。如何在其他组件中使用有关点击次数的信息?
答案 0 :(得分:1)
下面是一个示例,当Button
与兄弟姐妹相关时,如何将数据发送到组件Info
App
|
|
--------|--------
| |
| |
Button Info
代码:
class App extends React.Component {
state = {
// Now the state is duplicated because clickCounter lives both
// inside Button and App. You could just leave the clickCounter in
// App and remove it from Button. Then you would also pass the
// clickCounter to Button as props as you pass it to Info.
// This way state would not be duplicated and in general it is advised
// in React to not duplicate state, although in this particular example, it doesn't do much harm IMHO.
clickCounter: 0
};
render() {
return (
<div>
<Button
clickHandler={cc => {
this.setState({ clickCounter: cc });
}}
/>
<Info counter={this.state.clickCounter} />
</div>
);
}
}
class Info extends React.Component {
render() {
return (
<div>
<p>Info: {this.props.counter}</p>
</div>
);
}
}
class Button extends React.Component {
state = {
clickCounter: 0
};
handleClick = () => {
this.props.clickHandler(this.state.clickCounter + 1);
this.setState(prevState => {
return { clickCounter: prevState.clickCounter + 1 };
});
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click</button>
<p>CLICKS: {this.state.clickCounter}</p>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
对于其他情况,请参考this。
答案 1 :(得分:0)
您可以在React中使用lifting state up完成什么。您必须将状态提升或使用Redux之类的全局存储解决方案才能将任何数据传递给同级。
Button
组件,以便您可以更改状态。
class App extends React.Component {
state = {
clickCounter: 0,
};
handleClick = () =>
this.setState( prevState => ( {
clickCounter: prevState.clickCounter + 1,
} ) );
render() {
const { clickCounter } = this.state;
return (
<div>
<Button onClick={this.handleClick}>Click</Button>
<p>CLICKS data in Parent: {clickCounter}</p>
<LvlChecker clickCounter={clickCounter} />
</div>
);
}
}
const Button = props => (
<div>
<button onClick={props.onClick}>Click</button>
</div>
);
const LvlChecker = props => (
<div>CLICKS data in LvlChecker: {props.clickCounter}</div>
);
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>