我想将渲染分为几个部分。
必须丢失一些代码位,因为我的真实代码超过一千行,例如这行。
基本上,我希望能够调用Page2
并使用handleSubmit
中的功能handleChange
和Page2
。但是当我打电话给Page2时,代码说他找不到handleSubmit和handleChange。我希望它能像没有将代码分成几个函数那样工作。如果有人有主意:/
所以我这样分离了我的代码:
Page1.js:
import {Page2} from './Page2';
const initialState = { test:'', test2: ''};
export default class Page1 extends Component {
constructor(props) {
super(props);
this.state = initialState;
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const InputValue = event.target.value;
const stateField = event.target.name;
this.setState({
[stateField]: InputValue,
});
console.log(this.state);
}
async handleSubmit(event) {
this.setState({ loading: true });
event.preventDefault();
const { test= ''} = this.state;
await axios.post(' (endpoint API)',
{ key1: `${test}`);
}
render() {
return (
<Tabs selectedIndex={this.state.tabIndex} onSelect={tabIndex => this.setState({ tabIndex })}>
<TabList>
<Tab >Non Dynamique</Tab>
<Tab> Automation </Tab>
</TabList>
<TabPanel>
<Input type="number" step="0.01" name="test" onChange={this.handleChange} value=
{this.state.test || ''}/> </Col>
<Button type="submit"> Update </Button>
</TabPanel>
<TabPanel>
{this.Page2}
</TabPanel>
);
}
}
第2页:
export class Page2 extends Component {
render() {
return(
<Input type="number" step="0.01" name="test2" onChange={this.handleChange} value=
{this.state.test || ''}/> </Col>
<Button type="submit"> Update </Button>
);
}
}
谢谢您的回复
您需要将page2
渲染为react组件,并将这些函数引用作为prop传递给类似对象。
<Page2 handleChange={this.handleChange} handleSubmit={this.handleSubmit} />
在Page2组件中,您可以在道具中获得以上功能参考。
export default class Page2 extends React.Component {
constructor(props) {
super(props);
this.state= {
}
}
render() {
const { handleSubmit, handleChange} = this.props
return(
<div>
<Input type="number" step="0.01" name="test2" onChange={handleChange} value=
{this.state.test || ''}/>
<Button type="submit" onSumbit={handleSubmit}> Update </Button>
</div>
)
}
}
<Page2 handleChange={this.handleChange} handleSubmit={this.handleSubmit} test={this.state.test}/>
第2页代码
export default render2 = (props) => {
return <div>
<Input type="number" step="0.01" name="test2" onChange={props.handleChange} value=
{props.test || ''}/> </Col>
<Button type="submit" handleSubmit={props.handleSubmit}> Update </Button>
</div>
};