【问题标题】:convert angularJS function to a react function将 angularJS 函数转换为反应函数
【发布时间】:2018-12-16 01:55:46
【问题描述】:

我目前正在尝试使用角度功能,但我无法在反应应用程序中使用 ng-click。

我正在尝试将以下函数转换为反应函数,我知道 axios,不确定如何在反应中处理刀片变量。

我需要将角度 sn-p 转换为反应函数。

Angular(main.js)

$scope.myfollow = function(user) {
    $http.post('/user/follow/'+ user.id).then(function(result) {
        console.log("user id is:"+ user.id);
    });
};

反应文件

render(){
    return(

       <div className="followdoe">      
            <button  onClick={ this.btnClick.bind(this) } className={this.state.className}>
                   <p>{ this.state.btnText }</p>
            </button>
       </div>


    )
}

Route.php

Route::post('user/follow/{id}', 'UserController@my_follow');

Profile.blade.php

<div style="margin:30px 0px;">

    <button class="follow-button" ng-click="myfollow({{$user}});">+ Follow</button>
</div>

UserController.php

    public function my_follow(Request $request, $id)
    {
        $user = auth()->user();

        if($user->id != $id && $otherUser = User::find($id)){

            $user->toggleFollow($otherUser);
        }

    }
   public function getProfile($user)
    {  
        $user = User::with(['posts.likes' => function($query) {
                            $query->whereNull('deleted_at');
                        }, 'follow','follow.follower'])
                      ->where('name','=', $user)->first();



        if(!$user){
            return redirect('404');
        }

        return view ('profile')->with('user', $user);
    }

【问题讨论】:

  • 你的 React 组件中有 user 数据吗?
  • 我不喜欢,我该怎么做
  • 您的问题是关于如何将您的 Angular myfollow 函数移植到 React。恐怕我不确定您的数据看起来如何。
  • 什么数据?我只是想要一种方法来制作相同的角度函数,但在反应中,你知道如何做到这一点吗?谢谢你

标签: javascript php angularjs laravel reactjs


【解决方案1】:

您可以在组件上创建一个函数并使用fetch API。

示例

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      className: "test",
      btnText: "Text",
      user: { id: 123 }
    };
    this.myfollow = this.myfollow.bind(this);
    this.btnClick = this.btnClick.bind(this);
  }

  myfollow(user) {
    fetch(`/user/follow/${user.id}`, { method: "POST" })
      .then(response => response.json())
      .then(response => {
        console.log(response);
      });
  };

  btnClick() {
    this.myfollow(this.state.user);
  };

  render() {
    return (
      <div className="followdoe">
        <button onClick={this.btnClick} className={this.state.className}>
          <p>{this.state.btnText}</p>
        </button>
      </div>
    );
  }
}

【讨论】:

  • 我的关注函数给出了一个语法错误,我正在努力解决
  • myfollow = user附近某处的意外令牌
  • @BARNOWL 好的。我更新了答案。您的开发环境中可能没有class fields,这是我以前版本的答案使用的。
  • 完美,构建成功让我试一试。
  • @BARNOWL 是的,这就是我上面的第二个问题。你的 React 组件中有 user 数据吗?由于您在 Angular 代码中使用 user.id,因此您需要为 URL 使用 user.id
猜你喜欢
  • 2020-02-14
  • 2016-06-02
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
相关资源
最近更新 更多