在以下两个代码中,有一个辅元件和一个主元件。子组件有一个TextField,而父组件有Dropdown,有没有一种方法可以将TextField值设置为我将parent Dropdown更改为的值?例如,如果我选择"Medium",我希望将子组件TextField的值更改为"Medium“。这个是可能的吗?
下面是子组件
import * as React from "react";
import { TextField } from 'office-ui-fabric-react/lib/';
const ChildComponent = (props) => {
return(
<TextField
label="Description" required
key="descriptionKey"
styles={props.styles}
value={props.value}
multiline={props.multiline}
onChange={props.onChange}
defaultValue={props.defaultValue}
placeholder={props.placeholder}
/>
);
}
export default ChildComponent;
下面是父组件
import * as React from "react";
import ChildComponent from './ListItem';
import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/';
class ParentComponent extends React.Component {
handleChange = (event) => {
this.setState({
operationType: event.target.value,
})
};
render(){
const riskAssess: IDropdownOption[] = [
{ key: 'high', text: 'High' },
{ key: 'medium', text: 'Medium' },
{ key: 'low', text: 'Low' },
]
return(
<div>
<Dropdown
label="Risk Assessment" required
ariaLabel="Risk"
styles={{ dropdown: { width: 125 } }}
options={riskAssess}
onChange={this._onChange}
/>
<ChildComponent value="This is what I want to change to Dropdown value" />
</div>
);
}
private _onChange = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
this.setState({operationType: item.text})
console.log(event);
};
}
export default ParentComponent;
发布于 2020-04-05 09:09:43
是啊!用{this.state.operationType}
替换"This is what I want to change to Dropdown value"
。大括号告诉JSX您想要一个变量来填充该值。
使用TypeScript,您的组件需要通过向React.Component添加泛型参数来定义其属性和状态结构:
interface ParentProps = {};
interface ParentState = {
operationType: string;
};
class ParentComponent extends React.Component<ParentProps, ParentState> {
对于ChildComponent,您可能希望以类似的方式扩展React.FC (FunctionalComponent的缩写)。因为它没有定义任何状态,所以它可以忽略第二个泛型参数:
interface ChildProps {
styles?: React.CSSProperties;
value?: string;
multiline?: boolean;
onChange?: React.ChangeEventHandler<HTMLInputElement>
defaultValue?: string;
placeholder?: string;
};
const ChildComponent: React.FC<ChildProps> = (props) => {
现在TypeScript知道该期待什么了。
TypeScript精确的接口定义确保每个组件只获取它允许的内容。它将React的PropTypes警告替换为强制编译错误。它更复杂,必须定义所有这些,但它有助于减少错误倾向的开发。
https://stackoverflow.com/questions/61036537
复制相似问题