我在Typescript中构建类似this React example的东西。目标是让父母拥有一个州,并创建几个无状态子组件,将他们的点击次数传递给父级。
由于示例是在Javascript中,我不知道输入框事件和onChange处理程序的类型是什么......?我已经尝试了几个选项,比如React.MouseEvent<HTMLInputElement>
,但这只是猜测......
父组件 创建imageRows并传递处理程序:
render() {
<div>
<ImageRow key={el.url} onChange={this.onChange}/>
</div>
}
// what should the type of e be?
onChange(e:any){
}
ImageRow组件
export interface ImageRowProps {
genre: Array<number>
url: string
onChange : any // what is the type of the callback function?
}
export class ImageRow extends React.Component<ImageRowProps> {
render() {
return <div className="imagerow">
<input type="checkbox" key={index} onChange={this.props.onChange} defaultChecked={(num == 1)}/>
</div>
}
修改
类似的问题只显示事件类型,而不是处理程序类型。当我更改事件类型时:
onChange(e: React.FormEvent<HTMLInputElement>){
console.log(e.target.value)
}
我收到此错误:
Property 'value' does not exist on type 'EventTarget'.
答案 0 :(得分:34)
答案 1 :(得分:0)
在我们的应用程序中,
console.log(event.target.value); //无效(空白值)
console.log(event.target.checked); //工作正常(true / false)
//../src/components/testpage2/index.tsx
import * as React from 'react';
import { TestInput } from '@c2/component-library';
export default class extends React.Component<{}, {}> {
state = {
model: {
isUserLoggedIn: true
}
};
onInputCheckboxChange = (event: React.ChangeEvent<HTMLInputElement>) => {
console.log(event.target.value); // Not Working
console.log(event.target.checked); // Working
const field = event.target.name;
const model = this.state.model;
model[field] = event.target.checked;
return this.setState({model: model});
};
render() {
return (
<div>
<TestInput name="isUserLoggedIn" label="Is User LoggedIn : " type="checkbox" onChange={this.onInputCheckboxChange} />
</div>
);
}
}
//=============================================================//
import * as React from 'react';
//import * as cs from 'classnames';
export interface TestInputProps extends React.HTMLAttributes<HTMLInputElement> {
name: string;
label: string;
onChange: React.ChangeEventHandler<HTMLInputElement>;
placeholder?: string;
value?: string;
type?: string;
error?: string;
className?: string;
}
export const TestInput : React.SFC<TestInputProps> = ({ name, label, onChange, placeholder, value, type, className, error, ...rest }) => {
let wrapperClass:string = 'form-group';
if (error && error.length > 0) {
wrapperClass += " " + 'has-error';
}
return (
<div className={wrapperClass}>
<label htmlFor={name}>{label}</label>
<div className="field">
<input
type={type}
name={name}
className="form-control"
placeholder={placeholder}
value={value}
onChange={onChange}/>
{error && <div className="alert alert-danger">{error}</div>}
</div>
</div>
);
}
TestInput.defaultProps ={
type: "text"
}