我有一个父组件和两个子组件。我想要创建一个按钮,当点击该按钮时,将打开一个对话框。因此,我将按钮和对话框作为父组件的两个子组件。我试图更改父组件的状态,使其在点击按钮时显示新的对话框,并重新渲染父组件,将这个值传递给对话框组件。但是对话框组件没有重新渲染。
我使用 TypeScript 和 React,不使用 Redux。
父组件:
export default class TilesRootComponent extends React.Component<ITilesRootProps, ITilesRootState>{
constructor(props: ITilesRootProps, state: ITilesRootState) {
super(props)
this.state = {
displayNewTileDialog: false
}
}
onClickNewTile(): void {
this.setState({
displayNewTileDialog: true
})
}
onHideNewTileDialog(): void {
this.setState({
displayNewTileDialog: false
})
}
render(): JSX.Element {
return (
<div className="tilesRootComponent">
<div className="ms-Grid" dir="ltr">
<div className="ms-Grid-row">
<AddNewButtonComponent buttonText="New Tile" onButtonClick= {() => this.onClickNewTile()} />
</div>
<div className="ms-Grid-row">
</div>
</div>
<NewTileDialogComponent displayNewTileDialog = {this.state.displayNewTileDialog} onHideNewTileDialog = { () => this.onHideNewTileDialog()}/>
</div>
)
}
}
按钮组件:
export default class AddNewButtonComponent extends React.Component<IAddNewButtonProps, IAddNewButtonState>{
constructor(props: IAddNewButtonProps, state: IAddNewButtonState) {
super(props)
}
render(): JSX.Element {
return (
<div className="addNewButtonComponent">
<CommandButton
data-automation-id="test"
iconProps={{ iconName: 'Add' }}
text={this.props.buttonText}
onClick={() => this.props.onButtonClick()} />
</div>
)
}
}
我的对话框组件是:
export default class NewTileDialogComponent extends React.Component<INewTileDialogProps, INewTileDialogState>{
constructor(props: INewTileDialogProps, state: INewTileDialogProps) {
super(props)
this.state = {
tileName: '',
tileImageUrl: '',
tileOrder: ''
}
}
saveTile() : void {
let result = `Tile name: ${this.state.tileName} \nimage url: ${this.state.tileImageUrl} \norder: ${this.state.tileOrder}`
alert(result)
}
render(): JSX.Element {
return (
<div className="newTileDialogComponent">
<Dialog
isOpen={this.props.displayNewTileDialog}
// onDismiss={this._closeDialog}
type={DialogType.largeHeader}
title='Add/Edit Tile'
subText='Modify or Add tile info in the below form: '>
<TextField label="Tile Name" value ={this.state.tileName} onChanged = {(newVal) => this.setState({ 'tileName': newVal})}/>
<TextField label="Image Url" value = {this.state.tileImageUrl} onChanged = {(newVal) => this.setState({ 'tileImageUrl': newVal})}/>
<TextField label="Order" value = {this.state.tileOrder} onChanged = {(newVal) => this.setState({ 'tileOrder': newVal})} />
<Button text="Submit" className={commonStyles.defaultButton } onClick = {() => this.saveTile()} />
<Button text="Discard" onClick = {() => this.props.onHideNewTileDialog()}/>
</Dialog>
</div>
)
}
}
我的理解是,当更改父组件的状态时,应该渲染所有子组件。在这种情况下我需要做什么?