我曾经将 ref 用于表单,但现在我总是为表单声明,我面临一个问题,即在用户提交某些内容后必须清除字段。
handleSumbit = (e) => {
e.preventDefault()
const todoText = this.state.todoText
if(todoText.length > 0){
this.refs.todoTextElem = "" // wont work
this.props.onAddTodo(todoText)
} else {
this.refs.todoTextElem.focus() //worked
}
}
render() {
return(
<div>
<form onSubmit={this.handleSumbit}>
<input ref="todoTextElem" type="text" onChange={e => this.setState({todoText: e.target.value})} name="todoText" placeholder="What do you need to do?" />
<button className="button expanded">Add Todo</button>
</form>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
清除 ref 根本不起作用,因为它是一个受控输入。我不想做一些愚蠢的事情
从父组件传递一个标志,告诉表单已提交,然后使用 setState 清除输入。或者让 onAddTodo 有一个回调,这样我就可以做
this.props.onAddTodo(todoText).then(()=>this.state({todoText:""}))
Run Code Online (Sandbox Code Playgroud) 我试图在反应中练习渲染道具,但是我遇到了错误
this.props.children不是函数
这是我的代码
import React from 'react';
import { render } from 'react-dom';
const Box = ({color}) => (
<div>
this is box, with color of {color}
</div>
);
class ColoredBox extends React.Component {
state = { color: 'red' }
getState() {
return {
color: this.state.color
}
}
render() {
return this.props.children(this.getState())
}
}
render(<ColoredBox><Box /></ColoredBox>, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)
我有无状态的反应
const Clock = () => {
const formatSeconds = (totalSeconds) => {
const seconds = totalSeconds % 60,
minutes = Math.floor(totalSeconds / 60)
return `${minutes}:${seconds}`
}
return(
<div></div>
)
}
export default Clock
Run Code Online (Sandbox Code Playgroud)
如何测试formatSeconds方法?
我写了这个,测试失败了。
import React from 'react'
import ReactDOM from 'react-dom'
import expect from 'expect'
import TestUtils from 'react-addons-test-utils'
import Clock from '../components/Clock'
describe('Clock', () => {
it('should exist', () => {
expect(Clock).toExist()
})
describe('formatSeconds', () => {
it('should format seconds', () => {
const Clock = …Run Code Online (Sandbox Code Playgroud) 我的以下HOC有什么问题?我收到无法将类作为函数的错误?
https://i.imgur.com/SirwcGZ.png
我的HOC
const CheckPermission = (Component) => {
return class App extends Component {
componentDidMount() {
this.props.fetchUsers().then(resp => {
this.setState({user: true, loading: false});
})
}
render() {
const { user, loading } = this.props
loading && <div>Loading...</div>
!user && <Redirect to="/dashboard" />
return <Component {...this.props} />
}
}
}
export default connect(state=>state.global, {fetchUsers})(CheckPermission)
Run Code Online (Sandbox Code Playgroud)
这就是我导入和用户CheckPermission的方式:
<Route exact path='/dashboard' component={CheckPermission(Dashboard)} />