项目作者: vnues

项目描述 :
react版的双向数据绑定-- r-model
高级语言: JavaScript
项目地址: git://github.com/vnues/babel-react-rModel.git


babel-react-rmodel

背景

处理react的表单组件是很麻烦的事,因为我们想要让它变成受控组件,这导致往往处理一个表单组件就要重复代码,所以为了提供r-model的语法糖来应对这种情况,当然这也是就是react版的双向数据绑定

如何使用

  1. class App extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state={
  5. inputVale:"🍺🍺hello react-model"
  6. }
  7. }
  8. render() {
  9. const {inputVale} =this.state
  10. return (
  11. <div>
  12. <input type="text" r-model={inputVale} />
  13. </div>
  14. )}
  15. }

编译后

  1. class App extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = {
  5. inputVale: "hello react-model"
  6. };
  7. }
  8. render() {
  9. const {
  10. inputVale
  11. } = this.state;
  12. return React.createElement("div", null, React.createElement("input", {
  13. type: "text",
  14. value: inputVale,
  15. onChange: e => {
  16. this.setState({
  17. [`${this.state.inputVale}`]: e.target.value
  18. });
  19. }
  20. }));
  21. }
  22. }

支持自定义的onChange事件回调函数

  1. class App extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state={
  5. inputVale:"🍺🍺hello react-model"
  6. }
  7. }
  8. alert=()=>{
  9. window.alert(this.state.inputVale)
  10. }
  11. render() {
  12. const {inputVale} =this.state
  13. return (
  14. <div>
  15. <input onChange={this.alert} type="text" r-model={inputVale} />
  16. </div>
  17. )}
  18. }

编译后

  1. class App extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. _defineProperty(this, "alert", () => {
  5. window.alert(this.state.inputVale);
  6. });
  7. this.state = {
  8. inputVale: "🍺🍺hello react-model"
  9. };
  10. }
  11. render() {
  12. const {
  13. inputVale
  14. } = this.state;
  15. return React.createElement("div", null, React.createElement("input", {
  16. onChange: e => {
  17. this.setState({
  18. [`${this.state.inputVale}`]: e.target.value
  19. });
  20. this.alert(e);
  21. },
  22. type: "text",
  23. value: inputVale
  24. }));
  25. }
  26. }