语境
我试图从另一个无状态组件中的无状态组件获取输入字段的值,然后使用它来调用方法。我正在为我的 UI 组件使用 rebass,并在 Meteor + Mantra 中执行此操作。
我知道如果我使用 <input>
,我可以通过使用 refs 来做到这一点HTML 字段而不是另一个无状态组件。
问题
我当前的代码产生未定义的 preventDefault,删除后,console.log 会在每次输入更改时打印出来,而不是在提交时打印出来。我相信我的状态适用于整个仪表板组件,而不是无状态的 Rebass <Input/>
, 但我不知道如何改变它。
import React from 'react';
import {PageHeader, Container, Input,Button} from 'rebass';
class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = { websiteUrl: ''};
this.onInputChange = this.onInputChange.bind(this);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onInputChange(event) {
this.setState({websiteUrl:event.target.value});
}
onFormSubmit() {
event.preventDefault;
const {create} = this.props;
const {websiteUrl} = this.state.websiteUrl;
console.log(this.state.websiteUrl);
create(websiteUrl);
}
render() {
const { error } = this.props;
return (
<div>
<PageHeader
description="Dashboard Page"
heading="Dashboard"
/>
<Container>
<form>
<Input
value={this.state.websiteUrl}
type="text"
buttonLabel="Add Website"
label="Website"
name="add_website"
onChange={this.onInputChange}
/>
<Button
backgroundColor="primary"
color="white"
inverted={true}
rounded={true}
onClick={this.onFormSubmit()}
> Add Website </Button>
</form>
</Container>
</div>
);
}
}
export default Dashboard;
最佳答案
您应该将一个事件
传递给onFormSubmit
函数:
<Button
backgroundColor="primary"
color="white"
inverted={true}
rounded={true}
onClick={(event) => this.onFormSubmit(event)}
...
关于javascript - 从无状态组件获取输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37492674/